C++17增加了constexpr lambda,可以将lambda表达式用于编译器常量。
#include <iostream>
using namespace std;
int main() {
auto constexpr f = [](auto a){return a*2;};
enum A{
D1 = f(2), //f(2)作为常量用于定义枚举
D2,
D3
};
cout<<D1<<D2<<D3<<endl;
int a = 2;
switch(a)
{
case f(1): //f(1)作为常量用于switch/case语句
cout<<"a=2"<<endl;
}
static_assert(f(3) == 6);
return 0;
}
运行程序输出:
456
a=2
需要说明的是,C++17开始当符合条件时会默认lambda表达式为constexpr,即使不使用这个关键字进行声明:
#include <iostream>
using namespace std;
int main()
{
auto f = [](int i){return i*2;};
char data[f(2)] = {0};
cout<<sizeof(data)<<endl;
return 0;
}
运行程序输出:
4