gpt4 book ai didi

c++ - 什么时候可以在 constexpr 成员函数中使用非常量成员?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:59 26 4
gpt4 key购买 nike

我遇到了一个我不明白的情况。有人会很好地解释为什么第一个代码编译正确而第二个代码编译错误吗:

error: the value of 'TestClass::z' is not usable in a constant expression
static constexpr int sum() {return x+y+z;}
----------------------------------------------------^
note: 'int TestClass::z' is not const static int z;"

工作代码:

#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;
}

但是当我尝试使 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;
}

附言我正在使用 mingw32-g++ 4.8.1

最佳答案

在第一种情况下,结果仅取决于函数的参数,包括用于访问 z 的隐式 this。这并不会使它失去 constexpr 的资格 - 如果所有参数都是常量表达式,那么结果也是。

在您的示例中,它不是常量表达式(因为 tc 不是),但这并不重要,因为它没有在需要常量表达式的上下文中使用。这是一个显示它在常量表达式中的用法的示例:

constexpr TestClass tc;
array<int, tc.sum()> a;
cout << a.size() << endl;

在第二种情况下,结果还取决于一个静态变量,其值可能会在程序运行期间发生变化。这确实取消了它的资格 - 即使所有参数都是常量表达式,z 不是,因此函数调用的结果永远不可能是常量表达式。

关于c++ - 什么时候可以在 constexpr 成员函数中使用非常量成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29349028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com