这个问题类似于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),
表示所有常量变量 SIZE
、SIZE2
和 E1
(因为它们已使用常量表达式初始化)在整型常量中有效-expression,因此可以用作非类型模板参数的模板参数。
关于c++ - 琐碎的整型 const 变量总是可以用作模板值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68760490/