c++ - 琐碎的整型 const 变量总是可以用作模板值吗?

标签 c++ templates

这个问题类似于this one ,但更具体到 c++11 之前的场景。

我注意到使用 Clang 和 g++ 时,以下代码可以编译并适用于 pre-c++11:

enum En { V0 = 0 };

template <int SZ> class C { };
template <En EN> class E { };

int main() {
    const int SIZE = 42;
    C<SIZE> c;
    const int SIZE2 = SIZE ^ 0xDEADBEEF;
    C<SIZE2> c2;
    const En E1 = V0;
    E<E1> e1;
}

在没有 constexpr 可用的上下文中,这样做非常方便,在某些情况下甚至可能是必要的。那么这是否保证有效,或者 g++ 和 Clang 只是为了方便而推断这些值?

最佳答案

So is this guaranteed to work

是的。来自 N1905 中的 [expr.const]/1 (这是 C++03-ish 标准版本):

5.19 Constant expressions [expr.const]

/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).

An integral constant-expression can involve only literals of arithmetic types (2.13, 3.9.1), enumerators, non-volatile const variables or static data members of integral or enumeration types initialized with constant expressions (8.5),

表示所有常量变量 SIZESIZE2E1(因为它们已使用常量表达式初始化)在整型常量中有效-expression,因此可以用作非类型模板参数的模板参数。

关于c++ - 琐碎的整型 const 变量总是可以用作模板值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68760490/

相关文章:

c++ - 依赖于规则的模板成员变量

wordpress - 如何让 WordPress 识别我新创建的页面模板?

c++ - 在模板特化中使用非类型模板模板参数

c++ - 传递给函数的字符串是 undefined symbol

c++ - 特殊类模板的类外构造函数定义

c++ - 我们可以在 C++ 中重载 `==` 运算符来比较两个字符串吗?

c# - 从 C# COM 方法返回对象和内存所有权

c++ - C++中类模板的自动编译时工厂注册

c++ - 在 Qt4 中创建可调整大小的侧边栏

C++ 创建固定大小的队列