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

标签 c++ string templates gcc const-reference

我正在尝试将 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/

相关文章:

c++ - 应该按什么顺序添加 float 以获得最精确的结果?

c++ - libuvc 程序无法编译

c++ - 字符串的异常行为

java - 如何将列表项转换为 int/double

c++ - 推断仿函数返回类型的通用方法?

C++ 连接 __FILE__ 和 __LINE__ 宏?

c++ - 没有任何功能的 C++ 多态类是否可能?

string - 从给定的单词最大化交叉点生成填字游戏

java - 如何在 NetBeans 7.1.1 中为日志消息创建代码模板

php - 即使未注册,也可以在 WooCommerceThankyou 页面上显示客户详细信息