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

标签 c++ class static constexpr

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

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/

相关文章:

javascript - 超出最大调用堆栈大小 - 无限循环

c# - 为什么静态类不能有析构函数?

c++ - 运行测试直到失败

c++ - QTCreator 中的运算符>>不匹配

c++ - 不同流状态的定义(C++)

c++ - 推断 lambda 的类型衰减为函数指针

c++ - 成员函数如何理解对象是通过取消引用 const 指针获得的?

php - 类中的文本方向不适用于 tr

c# - 在泛型函数中访问类型名称的静态字段

C++ Win32静态控件透明背景