constexpr的用法


#include 
#include <string>
#include 

// constexpr可以用来修饰变量或者函数
// constexpr含义是编译时期可以确定的常量
// constexpr用来修饰变量的时候,必须立刻赋值,并且
// constexpr变量赋值的右边必须是可以在编译期计算得到的,比如字面量或者constexpr函数或者constexpr修饰的构造函数
void VarConstexpr() {
  constexpr int x = 1;       // OK
  constexpr double y = 1.3;  // OK
}

// C++11标准中,constexpr function只能包含return语句,并且不能修改参数a,b的值
// 除了return之外的空语句、using、typedef等语句,也可以。因为不产生实际影响。
// 除了return语句之外,可以使用字面量、constexpr函数。不能调用non-constexpr函数!
constexpr int FuncConstexpr01(int a, int b) { return (a + b); }

// 当constexpr function用于constexpr变量赋值的时候,constexpr function是编译时期运算的
// 如果是non-constexpr变量的赋值,或者其他情况。constexpr function和普通函数完全一样,是运行期执行的。
void VarConstexpr2() {
  constexpr int x = 1 + FuncConstexpr01(2, 3);  // 编译时期执行,参数2和3都是必须是字面量
  int tmp = 1, tmp2 = 2;
  int y = 1 + FuncConstexpr01(tmp, tmp2);  // 运行期执行,和普通函数完全一样。
}

// C++14中对constexpr进行了扩展,constexpr function可以包含其他的语句。
#if __cplusplus >= 201402L
constexpr int FuncCpp14(int a, int b) {
  for (int i = 0; i < 100; i++) {
    a += i;
  }
  return (a + b);
}
#endif

int main() {
  VarConstexpr2();
#if __cplusplus >= 201402L
  std::cout << " C++14 " << std::endl;
  constexpr int x = FuncConstexpr01(1, 2) + 3;
#endif
  return 0;
}
cpp