gpt4 book ai didi

c++ - 作为非类型模板参数的常量字符串引用

转载 作者:行者123 更新时间:2023-11-30 05:44:30 25 4
gpt4 key购买 nike

我正在尝试将 const 字符串引用作为非类型模板参数,我无法克服此编译错误。

测试.h :

#include <string.h>
#include <iostream>

template<const std::string& V> class TestTmplt
{

};

const std::string& TEST_REF = "TESTREF" ;
typedef TestTmplt<TEST_REF> TestRefData ;

测试.cpp :

#include <test.h>

template class TestTmplt<TEST_REF> ;

编译错误:

./test.h:10:34: error: could not convert template argument âTEST_REFâ to âconst string& {aka const std::basic_string<char>&}â
./test.h:10:49: error: invalid type in declaration before â;â token

我在 centos linux 上编译,使用下面的 gcc 命令

g++ -c -MMD -MF test.u -g -D_LINUX -std=c++03 -pthread -Wall -DVALGRIND -Wno-missing-field-initializers -z muldefs -I.  -o test.o test.cpp

最佳答案

问题是 TEST_REF 不是 std::string 类型,而是 const std::string & 类型,即不是 std::string 类型的对象,因此不能用作模板参数。稍微改变一下,它就可以工作了:

#include <string>

template<const std::string& V> class TestTmplt
{

};

std::string TEST_REF = "TESTREF";

template class TestTmplt<TEST_REF>;

[Live example]

关于c++ - 作为非类型模板参数的常量字符串引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com