c++ - 非类型模板参数

标签 c++ templates

我知道非类型模板参数应该是一个常量整数表达式。有人可以解释为什么会这样吗?

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/

相关文章:

python - 在另一个应用程序中使用另一个 django 应用程序的模板

c++ - if constexpr 和 requires-expression 用于临时概念检查

c++ - 跟踪简单的递归函数

c++ - C++中随机访问归档的奇怪问题

c++ - 如何使用CUDA以正确的方式在C++项目和C++中的DLL之间传输数据?

c++ - 以模板类作为参数专门化模板结构

c++ - 将 char 数组类型转换为结构(不是类/对象)

c++ - 编译时函数选择取决于类型大小

c++ - C++通过迭代器确定变量类型

c++ - 创建列表/节点类程序的模板版本时遇到麻烦