我希望C类有一个类型为C的静态constexpr成员.这在C++ 11中是否可行?
尝试1:
struct Foo {
constexpr Foo() {}
static constexpr Foo f = Foo();
};
constexpr Foo Foo::f;
Run Code Online (Sandbox Code Playgroud)
g ++ 4.7.0说:'无效使用不完整类型'指的是Foo()调用.
尝试2:
struct Foo {
constexpr Foo() {}
static constexpr Foo f;
};
constexpr Foo Foo::f = Foo();
Run Code Online (Sandbox Code Playgroud)
现在的问题是在类定义中缺少constexpr成员的初始化器f.
尝试3:
struct Foo {
constexpr Foo() {}
static const Foo f;
};
constexpr Foo Foo::f = Foo();
Run Code Online (Sandbox Code Playgroud)
现在g ++抱怨重新声明Foo::f不同的内容constexpr.
我有以下Foo带嵌套类的示例类Bar,一切都是constexpr:
class Foo
{
private:
template <typename T>
struct Bar
{
constexpr Bar(){}
constexpr int DoTheThing() const
{
return 1;
}
};
public:
constexpr static auto b = Bar<int>{};
constexpr Foo() {}
constexpr int DoTheThing() const
{
return b.DoTheThing();
}
};
Run Code Online (Sandbox Code Playgroud)
我想测试那个调用Foo::DoTheThing返回1:
int main()
{
constexpr Foo f;
static_assert(f.DoTheThing() == 1, "DoTheThing() should return 1");
}
Run Code Online (Sandbox Code Playgroud)
GCC和Clang都在这里抱怨,但MSVC没有
GCC说:
错误:
constexpr Foo::Bar<T>::Bar() [with T = int]在定义之前使用Run Code Online (Sandbox Code Playgroud)constexpr static auto b = …