roz*_*ina 12 c++ constexpr c++14
我有以下代码:
struct Foo
{
struct Bar
{
std::uint32_t x = -1;
constexpr Bar(std::uint32_t x) : x(x) {}
};
static constexpr Bar CONST_BAR = Bar(0);
};
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,出现以下错误:
错误:'constexpr Foo::Bar::Bar(uint32_t)' 在定义完成之前在常量表达式中调用
有人可以向我解释发生了什么吗?据我所知,Bar 的构造函数是在第一次调用之前定义的。
我没有详细的解释,但我碰巧也偶然发现了这个问题,并认为它至少值得一提...除了将定义放在CONST_BARstruct 之外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";
}
Run Code Online (Sandbox Code Playgroud)