c++c++11constexprstatic-membersincomplete-type

Can't a class have static constexpr member instances of itself?


This code is giving me incomplete type error. What is the problem? Isn't allowed for a class to have static member instances of itself? Is there a way to achieve the same result?

struct Size
{
    const unsigned int width;
    const unsigned int height;

    static constexpr Size big = { 480, 240 };

    static constexpr Size small = { 210, 170 };

private:

    Size( ) = default;
};

Solution

  • Is there a way to achieve the same result?

    By "the same result", do you specifically intend the constexpr-ness of Size::big and Size::small? In that case maybe this would be close enough:

    struct Size
    {
        const unsigned int width = 0;
        const unsigned int height = 0;
    
        static constexpr Size big() {
            return Size { 480, 240 };
        }
    
        static constexpr Size small() {
            return Size { 210, 170 };
        }
    
    private:
    
        constexpr Size() = default;
        constexpr Size(int w, int h )
        : width(w),height(h){}
    };
    
    static_assert(Size::big().width == 480,"");
    static_assert(Size::small().height == 170,"");