【问题标题】:Assigning a lambda within a switch statement [duplicate]在 switch 语句中分配 lambda [重复]
【发布时间】:2019-01-06 10:34:06
【问题描述】:

我想根据一个变量的值来定义一个 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 语句完成后保留它以供使用?

【问题讨论】:

  • 由于您的 lambda 是无捕获的,因此您应该特别检查 this answer,即,您应该将您的 lambda 转换为指向函数的指针。
  • 您可以简单地在第一个 lambda 之前添加一个 +auto valueFunction = +[](...){...};。它将 lambda 转换为函数指针,因此 auto 将被推断为函数指针。

标签: c++ lambda switch-statement c++17


【解决方案1】:

您不能这样做,因为每个lambda 都有唯一的类型,并且它们不能相互分配。您可以改用std::function

std::function<int(int,int,int,int)> valueFunction = [](int s, int d, int ct, int tt) { return -1; };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多