0

I want to define a lambda based on the value of a variable, so I am using a switch statement.

However, I can't seem to work out how to type the variable that holds the lambda.

I've tried this:

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;
    }

and also just defining:

auto valueFunction;

But, with the above code, as soon as it tries to reassign valueFunction, the compiler errors (no match for operator "=").

So, how can I create a lambda inside a switch statement, and retain it for use after the switch statement is finished?

  • Since your lambda are captureless, you should check [this answer](https://stackoverflow.com/a/38621686/2666289) in particular, i.e., you should convert your lambda to pointer to function. – Holt Jan 06 '19 at 10:40
  • You could simply add a `+` before the first lambda: `auto valueFunction = +[](...){...};`. It would convert the lambda to a function pointer, so `auto` would be deduced as a function pointer. – HolyBlackCat Jan 06 '19 at 10:43

1 Answers1

1

You can't do that because every lambda has unique type, and they can't be assigned to each other. You can use std::function instead.

std::function<int(int,int,int,int)> valueFunction = [](int s, int d, int ct, int tt) { return -1; };
songyuanyao
  • 169,198
  • 16
  • 310
  • 405