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

后端 未结 2 2082
[愿得一人]
[愿得一人] 2020-12-06 20:25

I have a template base class, whereby subclasses are expected to pass themselves as the template parameter.

It looks a little like this:

template<         


        
相关标签:
2条回答
  • 2020-12-06 20:53

    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);
    };
    
    0 讨论(0)
  • 2020-12-06 21:05

    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.

    0 讨论(0)
提交回复
热议问题