0

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?

Light Alex
  • 49
  • 1
  • 7

1 Answers1

3

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.

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
  • What's the `+` for? 5.1.2 [expr.prim.lambda]: "lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator" https://stackoverflow.com/a/28746827/8918119 – Mihayl Dec 04 '17 at 13:49
  • Is it ok to use std::function? Here https://stackoverflow.com/a/28746827 dude said that std::function is heavy weight. Is there another way? – Light Alex Dec 04 '17 at 14:01
  • @LightAlex - You are already to the point of optimizing your code? Focus on correctness first. – StoryTeller - Unslander Monica Dec 04 '17 at 14:05
  • 1
    @A.A - The `+` is to explicitly cause a coercion to a pointer type. – StoryTeller - Unslander Monica Dec 04 '17 at 14:06
  • @LightAlex "Heavy weight" as in it is what a lot of other languages do implicitly and regularly, but not so much in C++. – Passer By Dec 04 '17 at 14:12
  • @StoryTeller - i'm writing a https request class. It's ready, but i detected a promblem with using callbacks. The point for the class is max speed. – Light Alex Dec 04 '17 at 15:18