我知道非类型模板参数应该是一个常量整数表达式。有人可以解释为什么会这样吗?
template <std::string temp>
void foo()
{
// ...
}
error C2993: 'std::string' : illegal type for non-type template parameter 'temp'.
我了解常量积分表达式是什么。像上面的代码片段那样不允许像 std::string
这样的非常量类型的原因是什么?
最佳答案
你不能这样做的原因是非常量表达式在编译时不能被解析和替换。它们可能会在运行时发生变化,这需要在运行时生成新模板,这是不可能的,因为模板是一个编译时概念。
以下是标准允许的非类型模板参数 (14.1 [temp.param] p4):
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
- integral or enumeration type,
- pointer to object or pointer to function,
- lvalue reference to object or lvalue reference to function,
- pointer to member,
std::nullptr_t
.
关于c++ - 非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5687540/