参见下面的代码,f()是在下面定义的,主函数被认为是格式错误吗?有人能给我解释一下吗?
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
}发布于 2017-01-14 07:24:57
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函数是很好的,但是它们的定义在第一次使用之前必须是可用的。
发布于 2017-01-14 07:14:38
constexpr必须在编译时,在使用它的每一点上都知道。
这与您不能声明不完整类型的变量本质上是一样的,即使该类型稍后在同一源中完全定义。
https://stackoverflow.com/questions/41647636
复制相似问题