简体   繁体   中英

static constexpr member variable initialization

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM