Skip to content

CPP 学习思考二:constexpr

constexpr 意思就是指编译期间就可以算出的常量。之前的 const 可以理解为【只读】。
目前我觉得 constexpr 主要是用在修饰函数,比如下面的示例。

// constexpr 声明factorial可以参与编译期的运算
template<int N> class C{};

constexpr int FivePlus(int x) {
  return 5 + x;
}

void f(const int x) {
  C<x> c1;            // Error: x is not compile-time evaluable.
  C<FivePlus(6)> c2;  // OK
}

Comments