constexpr对非const对象的引用 [英] constexpr reference to non-const object
问题描述
是否可以将非常量引用声明为constexpr
?示例代码:
Is it permitted to declare a non-const reference as constexpr
? Example code:
int x = 1;
constexpr int& r = x;
这被gcc和clang接受(我尝试了两个当前和过去的版本,回到C ++ 11,都接受了).但是我认为它不应该被接受,因为C ++ 14 [dcl.constexpr/9]说:
This is accepted by gcc and clang (I tried several current and past versions of both, back to C++11, and all accepted it). However I think it should not be accepted because C++14 [dcl.constexpr/9] says:
如果在引用声明中使用constexpr说明符,则每个完整的- 初始化程序中出现的表达式应为常量表达式
if a constexpr specifier is used in a reference declaration, every full- expression that appears in its initializer shall be a constant expression
和x
不是常数表达式.
[dcl.constexpr]的最新C ++ 17草案中的语言已更改,甚至不再明确提及constexpr
引用,我无法说出它试图说的话.他们.
The language in the latest C++17 draft of [dcl.constexpr] changed and doesn't even mention constexpr
references explicitly any more, I can't make head nor tail of what it is trying to say about them.
推荐答案
假定x
具有静态存储期限,则左值表达式x
是一个完全有效的常数表达式.
Assuming that x
has static storage duration, the lvalue expression x
is a perfectly valid constant expression.
如果在需要prvalue的上下文中使用x
,这会导致从左值到右值的转换被应用,那么生成的prvalue表达式-称为TO_RVALUE(x)
-将不是常量表达式,原因很明显.但是在引用绑定的情况下,没有这种转换.
If you use x
in a context that requires a prvalue, which causes the lvalue-to-rvalue conversion to be applied to it, then the resulting prvalue expression - call it TO_RVALUE(x)
- would not be a constant expression, for obvious reasons. But in the case of reference binding, there is no such conversion.
这篇关于constexpr对非const对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!