c++ - 必须预先定义 constexpr 函数?

标签 c++ constexpr

请看下面的代码,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/

相关文章:

c++ - 构造函数 Parent 在构造函数 Child 的初始化列表中被调用

c++ - (不完全)constexpr 模板参数的要求

c++ - 为什么我应该更喜欢类中的 static constexpr int 而不是类级整数常量的枚举?

c++ - 在编译时使用枚举作为索引分配数组的值 (C++)

c++ - 用 C++ 进行 const 初始化

c# - 什么是标记接口(interface)?

c++ - 将 &mreq 参数传递给 setsockopt 方法时收到错误

c++ - 我们可以在 constexpr 函数中省略局部变量的 const 吗?

c++ - OpenCV - BFMatcher 只检查对象特征之间的距离,而不检查场景特征之间的距离?

c++ - 使用 Pimpl 的高级变体时可能会影响性能?