Light Alex
Light Alex

Reputation: 49

How to call a function with a reference lambda function?

Code:

typedef void(*callbackType) (int);

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
  int localVar = 5;
  setit([](int num) {
    std::cout << localVar; // there is an error here
  });
}

I need to use localVar in lambda function that i send to setit

I guess i have to use [&]{ }

But how can i do it? How should i declare setit and globalCallback?

Upvotes: 0

Views: 98

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

There are some problems with the code above.

If you didn't need to capture anything, you could use + with lambda to convert it to a function pointer:

typedef void(*callbackType)(int);

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
  setit(+[](int){});
}

But this trick works with capturless lambdas only.

One possible solution is to change callbackType and use std::function instead:

using callbackType = std::function<void(int)>;

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
    int localVar = 5;

    setit([localVar](int num) {
        std::cout << localVar; // there is an error here
    });
}

which works well.

Upvotes: 3

Related Questions