我有以下代码:
class MyClass
{
static constexpr bool foo() { return true; }
void bar() noexcept(foo()) { }
};
Run Code Online (Sandbox Code Playgroud)
我希望,因为它foo()是一个static constexpr函数,并且因为它是在bar声明之前定义的,所以这是完全可以接受的.
但是,g++给我以下错误:
error: ‘static constexpr bool MyClass::foo()’ called in a constant expression
Run Code Online (Sandbox Code Playgroud)
这是......不太有用,因为在常量表达式中调用函数的能力是整个点constexpr.
clang++更有帮助.除了声明参数noexcept必须是常量表达式的错误消息之外,它还说:
note: undefined function 'foo' cannot be used in a constant expression
note: declared here
static constexpr bool foo() { return true; }
^
Run Code Online (Sandbox Code Playgroud)
那么......这是一个两遍编译问题吗?问题是编译器在定义任何成员函数之前是否尝试声明它们中的所有成员函数?(注意,在类的上下文之外,编译器都不会抛出错误.)这让我感到惊讶; 直观地说,我认为static constexpr成员函数不能在任何和所有常量表达式中使用,无论是在类中还是在类中.
此代码编译:
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}
};
};
Run Code Online (Sandbox Code Playgroud)
此代码不会:
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 = …Run Code Online (Sandbox Code Playgroud)