为什么常量变量是模板特殊化所必需的,而不是常量
Why is const variable necessary for template specialization over constants
我正在努力理解常量模板专业化。考虑以下具有一个专门化的模板函数:
enum class NodeType
{A, B, C};
template<NodeType>
bool afunc()
{
cout<<"calling generic"<<endl;
}
template<>
bool afunc<NodeType::A>()
{
cout<<"calling specific"<<endl;
}
我能够调用如下所示的专用实例:
const NodeType x = NodeType::A;
afunc<x>();
然而,若我移除const,那个么编译器会抱怨模板/参数推导失败。为什么const是必要的?
模板只是编译时的东西。如果删除const
,则x
不再是编译时常数,因此不能用于模板参数。
还要注意,x
只是一个编译时常数,因为您在初始化时就这样定义它。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我可以通过引用修改常量返回
- 如何创建长度由常量参数指定的数组
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 隐式常量/非常量运算符布尔
- 非常量变量只读位置的赋值
- 为什么常量变量是模板特殊化所必需的,而不是常量