我有以下的代码:
class MyClass
{
static constexpr bool foo() { return true; }
void bar() noexcept(foo()) { }
};
我原以为由于foo()
是一个static constexpr
函数,并且它在bar
被声明之前被定义,所以这应该是完全可以接受的。
然而,g++
却给我以下错误:
error: ‘static constexpr bool MyClass::foo()’ called in a constant expression
这并没有什么帮助,因为在常量表达式中调用函数的能力是constexpr
的全部意义所在。
clang++
则更加有用,除了一个错误信息,指出noexcept
的参数必须是常量表达式,它还显示:
note: undefined function 'foo' cannot be used in a constant expression
note: declared here
static constexpr bool foo() { return true; }
^
所以...这是一个需要两次编译的问题吗?是编译器试图在定义任何成员函数之前声明类中的所有成员函数所引起的问题吗?(注意,在类的上下文之外,没有编译器会报错。)这让我很惊讶;直觉上,我不认为static constexpr
成员函数不能在类内外的所有常量表达式中使用。
noexcept
表达式之前,bar
的主体并不完整,因此没有不一致性。 - Kyle Strandauto
示例说明了其中的一个问题。 - M.M