Hur*_*hen 8 c++ static-members constexpr c++11
在编写我的初始问题时,如果这是可能的,我偶然发现了与定义类相同类型的静态constexpr成员的问题,这很清楚地回答了我的干净解决方案无法用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;
};
Run Code Online (Sandbox Code Playgroud)
所以我在重述我的问题:为什么one编译的解决方案可以像你期望的那样使用,但是下面的解决方案会给出使用不完整类的错误?
class MyEnum
{
public:
// snip...
static constexpr const MyEnum two = MyEnum(2);
static constexpr const MyEnum three = 3;
// snip...
}
Run Code Online (Sandbox Code Playgroud)
由于@dyp提到了one编译解决方案,因为函数定义是在类主体之后编译的.所以它就像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 ^^^^
Run Code Online (Sandbox Code Playgroud)
另一方面,类主体中的定义在它们放置在类主体中时被编译.所以,当two和three被编译的类还没有完全确定.