我试图弄清楚GCC或Clang是否在这里以不同/错误的方式解释C 17标准.
这是我的代码,它使用GCC 8编译,但不使用Clang 6:
struct BoolHolder { constexpr static bool b = true; }; template<bool b> class Foo {}; int main() { BoolHolder b; Foo<b.b> f; // Works BoolHolder & br = b; Foo<br.b> f2; // Doesn't work }
我不知道这是为什么.显然,b.b是有效的constexpr(或者第一个Foo< b.b>无效). br.b不是有效的constexpr吗?为什么?对象或引用本身应该与它无关,因为我们在这里访问静态constexpr成员,对吧?
如果这真的无效C 17,那么GCC甚至不会警告我(即使我启用-Wall -Wextra -pedantic)这个事实应该被认为是一个错误吗?
解决方法
Clang是对的.可以说,参考文献在常量表达式中“热切地”评估. [expr.const] /2.11:
An expression
e
is a core constant expression unless the evaluation
of e,following the rules of the abstract machine,would evaluate one
of the following expressions:
- […]
- an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and
either
- it is initialized with a constant expression or
- its lifetime began within the evaluation of
e
;- […]