static constexpr member variable initialization

Viewed 364

I have the following code:

struct Foo
{       
    struct Bar
    {
        std::uint32_t x = -1;

        constexpr Bar(std::uint32_t x) : x(x) {}
    };

    static constexpr Bar CONST_BAR = Bar(0);
};

When I try to compile it I get the following error:

error: ‘constexpr Foo::Bar::Bar(uint32_t)’ called in a constant expression before its definition is complete

Can someone explain to me what is going on? As far as I can see Bar's constructor is defined before the first call.

Live example

2 Answers

I don't have a detailed explanation but I happened to have stumbled upon this problem as well and thought it was at least worth mentioning... Other than placing the definition of CONST_BAR outside of struct Foo, another possible workaround is instantiating Foo:

// Example program
#include <iostream>
#include <string>

template<typename T = void>
struct Foo
{       
    struct Bar
    {
        std::uint32_t x = -1;
    
        constexpr Bar(std::uint32_t x) : x(x) {}
    };
    
    static constexpr Bar CONST_BAR = Bar(0);
};

int main()
{
    std::cout << "x: " << Foo<>::CONST_BAR.x << "\n";
}

You might wanna try to initialize like this-

static constexpr Foo::Bar CONST_BAR = Foo::Bar(0);

outside struct Foo because the declaration of struct foo must complete.

Related