Initializing a static constexpr from an incomplete type because of a template base class

可紊 提交于 2019-11-28 01:28:19

I think you shall use lazy initialization. Actually Derived is still incomplete type; because the compiler don't know its size yet.

So the code shall be:

struct Derived : public Base<Derived>
{
    constexpr Derived(int x) : Base(x) {}

    static constexpr Derived getLIFE()
    {
        return Derived(34);
    }
};

EDIT: Same incomplete type behavior can be reproduced using this snippet:

struct MyStruct
{
    static constexpr int x = sizeof(MyStruct);
};

You can simply add constexpr to the definition of LIFE:

constexpr Derived Derived::LIFE = Derived(42);

Until recently GCC had a bug where it rejected this; you'll need to use either Clang or GCC 4.9.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!