与 class 定义相同类型的静态 constexpr 成员(其他详细信息)

Static constexpr members of same type as class defined (additional details)

在写我最初的问题时,如果这甚至可能的话,我偶然发现了这个问题 static constexpr member of same type as class being defined,它非常清楚地回答了我的干净解决方案在 C++11 中是不可能的。

但后来我想出了这段代码,它与原始海报非常接近,我想实现:

class MyEnum
{
public:
    constexpr MyEnum() : m_null(true), m_value(0) { }
    constexpr MyEnum(const unsigned int v) : m_null(false), m_value(v) { }

    constexpr operator unsigned int() const { return m_value; }

    static constexpr const MyEnum one() { return MyEnum(1); }

private:
    bool m_null;
    unsigned int m_value;
};

所以我要重新表述我的问题:为什么 one 的解决方案可以编译并可以按您预期的那样使用,但以下解决方案会给出有关使用不完整 class 的错误?

class MyEnum
{
public:
    // snip...

    static constexpr const MyEnum two = MyEnum(2);
    static constexpr const MyEnum three = 3;

    // snip...
}

正如@dyp 提到的,one 的解决方案是编译的,因为函数定义是在 class 主体之后编译的。所以就像 one 已经这样声明了

class MyEnum
{
public:
    static constexpr const MyEnum one();
    //... Definition here
};  //Class is fully defined after here

inline static constexpr const MyEnum MyEnum::one() { return MyEnum(1); }
                      //Fine here because class is complete ^^^^

另一方面,class 主体中的定义在 class 主体中被编译。所以当 twothree 被编译时 class 还没有完全定义。