为什么常量变量是模板特殊化所必需的,而不是常量

Why is const variable necessary for template specialization over constants

本文关键字:常量 特殊化 变量 为什么      更新时间:2023-10-16

我正在努力理解常量模板专业化。考虑以下具有一个专门化的模板函数:

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只是一个编译时常数,因为您在初始化时就这样定义它。