constexpr
语法从C++ 11
开始支持,所以要注意配置编译环境到支持的标准版本。例如用g++
编译。则需要添加-std=c++11
。
示例命令如下
g++ -std=c++11 main.cpp
当然了你可以选择更高版本进行编译,毕竟向前兼容,例如-std=c++2a
。
在C++
中,const
的语义是用于修饰一个变量或者成员函数的只读属性。例如:
const int a = 100;
所以从语义上来讲,const
并不代表一个 编译期常量 。而为了更有效的利用C++
的模板技术,并且将尽可能多的代码在编译期进行优化,C++11
引入了constexpr
,它的作用就是用来修饰一个编译期的常量。
在某些场景下,constexpr
和const
的作用是一致的。
const int a = 100;
constexpr int b = 100;
std::array<int, a> arr1;
std::array<int, b> arr2;
但是constexpr
有更重要的作用,就是用来修饰函数,当一个函数被constexpr
修饰后,编译器会针对该函数执行如下优化:当该函数被调用时,如果该函数的执行结果可以在编译期确定,那么编译器就会把执行结果当做编译期常量替换,否则还是作为运行时函数调用。
如下例子:
#include <array>
#include <iostream>
using namespace std;
constexpr int MUL(int a, int b) {
return a * b;
}
int main(int argc, const char * argv[]) {
array<int, MUL(5, 5)> a;
printf("size of a = %d\n", (int)a.size()); // size of a = 25
int b = 5;
b += 5;
// array<int, MUL(b, b)> c; // 左侧语句会编译失败,因为MUL(b, b)无法在编译时确定运算结果
const int c = 6;
array<int, MUL(c, c)> d;
printf("size of d = %d\n", (int)d.size()); // size of d = 36
return 0;
}
在以上例子中,MUL(5, 5)
和MUL(c, c)
可以在编译期确定结果,所以作为编译期常量传入可行,而MUL(b, b)
中由于变量b
是非常量,所以无法在编译期确定执行结果,于是array<int, MUL(b, b)> c;
语句编译失败。
对移动开发感兴趣的小伙伴可以加我公众号“风海铜锣”。