1

我试图将 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

我正在使用以下 gcc 命令在 centos linux 上编译

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
4

1 回答 1

1

问题是它TEST_REF不是 type std::string,而是 type const std::string &,即它不是 type 的对象,std::string因此不能用作模板参数。稍作改动,它就可以工作:

#include <string>

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

};

std::string TEST_REF = "TESTREF";

template class TestTmplt<TEST_REF>;

[现场示例]

于 2015-04-22T14:13:47.483 回答