[英]When non-const members can be used in constexpr member functions?
I encountered a situation I don't understand. 我遇到了一个我不明白的情况。 Would somebody be so nice to explain why first code compiles correctly while second gives an error:
有人会这么好解释为什么第一个代码正确编译而第二个代码出错:
error: the value of 'TestClass::z' is not usable in a constant expression
错误:'TestClass :: z'的值在常量表达式中不可用
static constexpr int sum() {return x+y+z;}static constexpr int sum(){return x + y + z;}
----------------------------------------------------^-------------------------------------------------- - ^
note: 'int TestClass::z' is not const static int z;"注意:'int TestClass :: z'不是const static int z;“
Working code: 工作代码:
#include <iostream>
using namespace std;
class TestClass
{
public:
constexpr int sum() {return x+y+z;}
private:
static constexpr int x = 2;
static const int y = 3;
int z = 5;
};
int main()
{
TestClass tc;
cout << tc.sum() << endl;
return 0;
}
But when I try to make TestClass::sum()
static I get aforementioned error: 但是当我尝试使
TestClass::sum()
静态时,我得到上述错误:
#include <iostream>
using namespace std;
class TestClass
{
public:
static constexpr int sum() {return x+y+z;}
private:
static constexpr int x = 2;
static const int y = 3;
static int z;
};
int TestClass::z = 5;
int main()
{
TestClass tc;
cout << tc.sum() << endl;
return 0;
}
PS I'm using mingw32-g++ 4.8.1 PS我正在使用mingw32-g ++ 4.8.1
In the first case, the result depends only on the function's arguments, including the implicit this
used to access z
. 在第一种情况下,结果只取决于该函数的参数,包括隐
this
用来访问z
。 This doesn't disqualify it from being constexpr
- if all the arguments are constant expressions, then so is the result. 这不会使它成为
constexpr
- 如果所有参数都是常量表达式,那么结果也是如此。
In your example, it isn't a constant expression (since tc
isn't), but that doesn't matter since it's not being used in a context that requires one. 在你的例子中,它不是一个常量表达式(因为
tc
不是),但这并不重要,因为它没有在需要一个的上下文中使用。 Here's an example showing its use in a constant expression: 这是一个示例,显示了它在常量表达式中的用法:
constexpr TestClass tc;
array<int, tc.sum()> a;
cout << a.size() << endl;
In the second case, the result also depends on a static variable, whose value could change during the program. 在第二种情况下,结果还取决于静态变量,其值可能在程序期间发生变化。 This does disqualify it - even if all the arguments are constant expressions,
z
isn't, and so the result of a function call can never be a constant expression. 这确实取消了它 - 即使所有参数都是常量表达式,
z
也不是,因此函数调用的结果永远不能是常量表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.