该代码编译:
struct Info
{
constexpr Info(bool val) : counted(false), value(unsigned(val)) {}
constexpr Info(unsigned val) : counted(true), value(val) {}
bool counted;
unsigned value;
};
constexpr const auto data = std::array{
Info{true}, Info{42u}
};
struct Foo
{
constexpr static inline const auto data = std::array{
Info{true}, Info{42u}
};
};此代码没有:
struct Foo
{
struct Info
{
constexpr Info(bool val) : counted(false), value(unsigned(val)) {}
constexpr Info(unsigned val) : counted(true), value(val) {}
bool counted;
unsigned value;
};
constexpr static inline const auto data = std::array{
Info{true}, Info{42u}
};
};报告的错误(在MSVC、gcc和clang中)表明,他们认为Info构造函数没有定义,或者不是constexpr,例如。来自clang:
prog.cc:21:5: note: undefined constructor 'Info' cannot be used in a constant expression
Info{true}, Info{42u}
^为什么?
(可能与this question相关,但Info在使用时应该是完整的;只有Foo仍然不完整。)
发布于 2019-02-13 07:36:02
gcc-8的错误信息可以说更清楚:
constexpr Foo::Info::Info(bool)’ called in a constant expression before its definition is complete
该错误似乎是根据expr.const§2产生的:
表达式
e是一个核心常量表达式,除非对e的计算遵循抽象机器(4.6)的规则计算下列表达式之一: ..。 (2.3) -调用未定义的constexpr函数或未定义的constexpr构造函数;
为什么它是未定义的,而调用显然是在定义之后?
问题是,成员函数定义被推迟到最外层的封闭类的结束大括号(因为他们可以看到封闭类的成员)。考虑一下这个类的定义:
constexpr int one = 1;
struct Foo
{
struct Bar
{
static constexpr int get_one() { return one; }
};
static constexpr int two = Bar::get_one() + 1;
static constexpr int one = 42;
};假设这应该有效,那么实现如何处理这一定义?
one is Bar::get_one指的是Foo::one,而不是::one,因此必须在看到该成员之后处理它。它在two的定义中使用,它是constexpr,因此必须在该成员的初始化项之前进行处理。因此,要使其工作,总的顺序必须是one,然后是get_one,然后是two。
但是C++实现不是这样工作的。他们不做任何复杂的依赖性分析。它们按照被看到的顺序处理声明和定义,除了class.mem§2中列出的一些例外情况。
在标准中,我似乎找不到明确的说法,直到oitermost封装类完成时,才会认为constexpr成员函数是未定义的,但这是唯一的逻辑可能性。它不能以任何其他方式工作。
https://stackoverflow.com/questions/54660899
复制相似问题