请看下面的代码,f() 是在下面定义的 main 函数被认为是病式的? 谁能给我一个解释?
constexpr int f ();
void indirection ();
int main () {
constexpr int n = f (); // ill-formed, `int f ()` is not yet defined
indirection ();
}
constexpr int f () {
return 0;
}
void indirection () {
constexpr int n = f (); // ok
}
最佳答案
C++14 标准提供了以下代码片段(为方便起见,我将其缩短):
constexpr void square(int &x); // OK: declaration
struct pixel {
int x;
int y;
constexpr pixel(int);
};
constexpr pixel::pixel(int a)
: x(a), y(x)
{ square(x); }
constexpr pixel small(2); // error: square not defined, so small(2)
// is not constant so constexpr not satisfied
constexpr void square(int &x) { // OK: definition
x *= x;
}
解决方案是将 square
的定义移动到 small
的声明之上。
从上面我们可以得出结论,前向声明 constexpr
函数是可以的,但是它们的定义必须在之前首次使用时可用。
关于c++ - 必须预先定义 constexpr 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41647636/