为什么const变量对于常量的模板特化是必需的

San*_*eep 1 c++ templates template-specialization

我试图了解常量模板专业化.考虑以下模板功能和一个专业化:

enum class NodeType
  {A, B, C};

template<NodeType>
bool afunc()
{
  cout<<"calling generic"<<endl;
}

template<>
bool afunc<NodeType::A>()
{
 cout<<"calling specific"<<endl;
}
Run Code Online (Sandbox Code Playgroud)

我能够调用专门的实例,如下所示:

 const NodeType x = NodeType::A;

  afunc<x>();
Run Code Online (Sandbox Code Playgroud)

但是,如果我删除const然后编译器抱怨模板/参数推断失败.为什么const必要?

Som*_*ude 7

模板只是编译时的事情.如果删除constx不再是编译时常量,因此不能用于模板参数.

另请注意,这x只是一个编译时常量,因为您可以使用初始化来定义它.