我有以下代码:
struct Foo
{
struct Bar
{
std::uint32_t x = -1;
constexpr Bar(std::uint32_t x) : x(x) {}
};
static constexpr Bar CONST_BAR = Bar(0);
};
当我尝试编译它时,出现以下错误:
error: ‘constexpr Foo::Bar::Bar(uint32_t)’ called in a constant expression before its definition is complete
有人可以向我解释发生了什么吗?据我所知,Bar 的构造函数是在第一次调用之前定义的。
Live example
最佳答案
我没有详细的解释,但我碰巧也偶然发现了这个问题,并认为它至少值得一提......除了放置CONST_BAR
的定义之外。结构之外 Foo
,另一种可能的解决方法是实例化 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";
}
关于c++ - 静态 constexpr 成员变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62147479/