how to initialize a constexpr reference
我试图初始化一个
1 2 3 4 5 6 7 8 9 10 11 12 | #include <iostream> constexpr int& f(int& x) // can define functions returning constexpr references { return x; } int main() { constexpr int x{20}; constexpr const int& z = x; // error here } |
但我有一个编译时错误
error: constexpr variable 'z' must be initialized by a constant expression
丢弃
error: binding of reference to type 'int' to a value of type 'const int' drops qualifiers
尽管我觉得
所以我的问题是:
PS:我已经看到了一些与我相关的问题,例如哪些值可以分配给"constexpr"引用?但我认为他们没有回答我的问题。
型
Are constexpr references ever useful? (i.e.,"better" than const references)
号
它们保证在程序启动之前被初始化,而对const的引用可以在程序启动运行之后的动态初始化期间初始化。
If yes, how can I effectively define them?
号
在概念上,引用等价于获取变量的地址,并且局部变量的地址不是常量(即使在
型
所以问题在于,一个COSTEXPR引用需要绑定到一个静态存储持续时间的对象,该对象覆盖在C++ 11标准草案中:N33 37节EDOCX1×2〔Exp.const〕(强调雷):
A reference constant expression is an lvalue
core constant expression that designates an object with static storage duration or a function
号
C++ 14标准草案:N39 36改变措辞:
A constant expression is either a glvalue core constant expression whose value refers to an object with static
storage duration or to a function, or a prvalue core constant expression whose value is an object where, for
that object and its subobjects:
- each non-static data member of reference type refers to an object with static storage duration or to a
function, and- if the object or subobject is of pointer type, it contains the address of an object with static storage
duration, the address past the end of such an object (5.7), the address of a function, or a null pointer
value.
号
因此,像这样更改
1 | constexpr static int x{20}; |
型
正如T.C.所说,初始值设定项需要是具有静态存储持续时间的对象。
N4140/§5.19/4 A constant expression is either a glvalue core
constant expression whose value refers to an object with static
storage duration [...]N4140/§7.1.5/9 A
constexpr specifier used in an object declaration
declares the object as const. Such an object shall have literal type
and shall be initialized. [...] Otherwise, or if aconstexpr
specifier is used in a reference declaration, every full-expression
that appears in its initializer shall be a constant expression.
号
在N3337中,措辞不同。