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

后端 未结 2 2091
[愿得一人]
[愿得一人] 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
    {
        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);
    };
    

提交回复
热议问题