在使用 constexpr 函数之前是否必须定义它们

Do constexpr functions have to be defined before they are used?

本文关键字:定义 是否 constexpr 函数      更新时间:2023-10-16

>见下面的代码,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函数,但它们的定义必须在首次使用之前可用。

constexpr某些

东西必须在编译时,在每个使用它的点上知道。

这本质上与不能声明不完整类型的变量相同,即使该类型稍后在同一源中完全定义也是如此。