0

I have a function that takes as an argument CallbackType, which is

typedef (*void) (const *char, bool)

I need to pass additional context, so I thought it would be a good idea to use lambdas:

CallbackType DelegateHandler(Pointer ptr) {
    return [&](const char* a, bool b) {
        callback(ptr, a, b); 
    };
}

It only works though if it's a capturing lambda, and a capturing lambda cannot be converted to a regular function pointer, so I get the error:

no known conversion for argument 1 from SetHandler(Pointer)::<lambda(const char*, bool)>’ to ‘CallbackType’ {aka ‘void(*)(const char*, bool)’ 

Any idea how to solve this in a simple fashion?

Mahoni
  • 7,088
  • 17
  • 58
  • 115

2 Answers2

3

As Michael already pointed out, closures can not be converted to function pointers.

It might be better to accept templated argument or std::function instead of raw function pointer, if there is such an option.

magras
  • 1,709
  • 21
  • 32
0

Lambda functions that contain captures are not convertible to normal function pointers. Check this and this SO question for more.

Generally, you have a callback that allows you to include a custom pointer which is passed, which will contain the extra data you want from the callback.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78