c++有两种常量:
一种是const:“i promise not to change this value”
一种是constexpr:”to be evaluated at compile time”
const 这种值可以在编译时或是运行时赋值,但constexpr的值只能在编译器确定
他们两的侧重点不同,就如上面英文写的那样
const侧重于值不变;constexpr侧重于编译期就确定值
还有以下几点是需要注意的:
如果一个constexpr变量的值来自于一个函数,那么这个函数必须是一个constexpr
eg: constexpr int fun () {} 而且这个函数必须尽量简单,函数体必须是一个return + 计算部分
constexpr函数也可以接受非const参数
下面的代码是可运行的
#include <iostream>
constexpr int dfun ( int x ) {
return x * 2;
}
int main() {
// non-const params
int v = 2;
int i = dfun ( v );
v = 1;
i = dfun ( v );
// const params
constexpr int a = 2;
int b = dfun ( a );
std::cout << i << std::endl << b << std::endl;
return 0;
}
常量表达式中的编译器计算主要是因为性能问题,在以下3种情况中,主要是因为c++语言规则:
case标签、模版参数、constexpr构造。
针对性能问题 不变性的概念是设计中比较重要的一部分
对于const,还是以前的理解的概念,对于constexpr,应该更多的应用于模版 泛型编程