13

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

4

2 Answers 2

2

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"; } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Then the declared variable will be in a different scope (global instead of foo)
Yeah, so therfore it's not the same and not a solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.