c++ - C++模板参数有什么要求?

标签 c++ templates parameters constants extern

如果您在 C++ 中使用采用整数值作为参数的模板,对于用作参数的整数变量是否有任何要求不同于在函数调用中将变量用作参数的要求?

这是问题 here 的后续问题.我特别想解决声明为函数或模板的“extern const int”的 WRT 变量是否存在差异?

我可以看到对于某些模板情况,编译时需要参数值。这总是真的吗?有没有一种方法可以指定(可能仅针对参数值的某些用途)在运行时使用该值?

最佳答案

以下内容来自标准

14.3.2.1:

A template-argument for a non-type, non-template template-parameter shall be one of:

  • an integral constant-expression of integral or enumeration type; or
  • the name of a non-type template-parameter; or
  • the address of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as & id-expression where the & is optional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or
  • a pointer to member expressed as described in 5.3.1 .

5.19.1:

In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case expressions (6.4.2), as bit-field lengths (9.6), as enumerator initializers (7.2), as static member initializers (9.4.2), and as integral or enumeration non-type template arguments (14.3).

 constant-expression:
            conditional-expression

An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type template parameters of integral or enumeration types, and sizeof expressions. Floating literals (2.13.3) can appear only if they are cast to integral or enumeration types. Only type conversions to integral or enumera- tion types can be used. In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, function-call, or comma operators shall not be used.

关于您之前的帖子,我相信“const 变量 ... 初始化 与 ...”部分的本质(我认为外部初始化不重要)。

关于c++ - C++模板参数有什么要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/643763/

相关文章:

c++ - 以十六进制格式在缓冲区中插入一个值

c++ - 用引号定义 C++ 预处理器宏

c++ - 我可以在 Visual Studio 中的 Lambda 中定义模板化函数

c++ - 指向指针(二维数组)的指针作为输入参数

reporting-services - SSRS根据多值参数对多个表进行分组

c++ - C++17中不定参数函数的错误

c++ - std::copy 钩子(Hook)

c++ - 如何从模板结构创建二维数组

C++ 嵌套 SFINAE 模板产生编译错误

c - 为什么需要将列数作为函数参数传递?