我想基于变量的值定义一个lambda,所以我正在使用switch语句。
但是,我似乎无法弄清楚如何键入保存lambda的变量。
我已经尝试过了:
auto valueFunction = [](int s, int d, int ct, int tt) { return -1; };
switch (changeMethod) {
case VeloChangeMethod::EXPONENTIAL_GROWTH:
valueFunction = [](int s, int d, int ct, int tt) { return /* maths goes here */ };
case VeloChangeMethod::EXPONENTIAL_DECAY:
valueFunction = [](int s, int d, int ct, int tt) { return /* maths goes here */ };
case VeloChangeMethod::NORMAL:
default:
valueFunction = [](int s, int d, int ct, int tt) { return /* maths goes here */ };
break;
}
,也只是定义:
auto valueFunction;
但是,使用上述代码,一旦尝试重新分配valueFunction
,编译器就会出错(运算符“ =”不匹配)。
那么,如何在switch语句中创建一个lambda,并在switch语句完成后保留它以供使用?
答案 0 :(得分:1)
您不能这样做,因为每个lambda都有唯一的类型,并且不能将它们彼此分配。您可以改用std::function
。
std::function<int(int,int,int,int)> valueFunction = [](int s, int d, int ct, int tt) { return -1; };