struct Foo
{
struct Bar
{
int data = 0;
//constexpr Bar() = default; // Doesn't work either
constexpr Bar() : data(0) {}
};
static constexpr Bar bar = {}; // ERROR
//static constexpr Bar bar = {0}; // Works if the ctor from Bar is removed
};
Clang and GCC (with std=c++20) say the constructor I'm trying to use is undefined. But it works if I change constexpr to inline. I would like to understand what is wrong with using 'contexpr'.
Compiler parses a class in two passes. The first pass handles member variables and function declarations, and the second pass handles function bodies, which is what allows you to use a member variable (or function) declared below a function in that function.
When classes are nested, the first pass runs over the entire outermost class (including all nested classes), then similarly the second pass over the entire outermost class (including nested ones).
Apparently, static variable initialization happens during the first pass. If it's non-
constexpr(inline), then seeing a constructor declaration is enough. But if it isconstexpr, then the constructor definition needs to be seen too (to immediately calculate the value), but it isn't available during the first pass.And when you get rid of the constructor and do
= {0}, that is aggregate initialization, which doesn't use a constructor at all, hence can work during the first pass.