[英]Non-const used in a constexpr : what does the standard say?
What does the C++11 iso standard say about such an expression : C ++ 11 iso标准对这样的表达式怎么说:
class MyClass
{
public:
constexpr int test()
{
return _x;
}
protected:
int _x;
};
_x
is a non-const used in a constexpr
: will it produce an error, or will the constexpr
be simply ignored (as when we pass a non-const parameter) ? _x
是在constexpr
使用的非常量:它将产生错误,还是会简单地忽略constexpr
(就像我们传递非常量参数时一样)?
It's perfectly fine, though somewhat useless: 很好,虽然没什么用:
constexpr int n = MyClass().test();
Since MyClass
is an aggregate, value-initializing it like that will value-initialize all members, so this is just zero. 由于
MyClass
是聚合,因此像这样对其进行值初始化将对所有成员进行值初始化,因此该值仅为零。 But with some polish this can be made truly useful: 但是,使用一些波兰语可以使它真正有用:
class MyClass
{
public:
constexpr MyClass() : _x(5) { }
constexpr int test() { return _x; }
// ...
};
constexpr int n = MyClass().test(); // 5
If the expression does not resolve to a constant expression, then it cannot be used as such. 如果表达式不能解析为常量表达式,则不能这样使用。 But it can still be used:
但仍然可以使用:
#include <array>
constexpr int add(int a, int b)
{
return a+b;
}
int main()
{
std::array<int, add(5,6)> a1; // OK
int i=1,
int j=10;
int k = add(i,j); // OK
std::array<int, add(i,j)> a2; // Error!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.