c++ - std::bind a regular function but with an epilogue -


i have particular callback (that defined in 'c' land) needs padded additional work not part of callback function. goes this...

typedef void (*callback_func)(int); extern int set_callback(callback_func cb); 

in c++ code, need set_value promise defined outside scope of callback, in class. so, i'd have capture std::promise member variable or alternatively this , send callback, set once callback has been invoked, compiler doesn't it. way,

set_callback([this](int x) {    // code ...      prom.set_value(true); }); 

below snipped error:

error: no matching function call 'set_callback'         set_callback([this](int var) {         ^~~~~~~~~~~~~~~~~~~~~~~~~ note: candidate function not viable: no known conversion '(lambda @ xxx ' 'callback_func'           (aka 'void (*)(int)') 1st argument 

i realize that, need somehow "bind" regular function make callback function std::function, unsure of way accomplish - not mention send parameter , perform epilogue. please suggest, thanks!

lambdas can decay function pointers if capture list empty. because code

[this](int x) {    // code ...      prom.set_value(true); } 

is equivalent to

struct somelambdaname {     mycapture self;      auto operator()(int x) const {         // code ...         self.prom.set_value(true);     } }; 

on other hand, function pointers that: pointers. pointer address of function call.

in c++, member function:

struct myclass {     int i;     int add_x(int x) { return = + x; } }; 

is c code (implementation dependent):

int add_x(myclass *self, int x) { return self->i = self->i + x; } 

if c code can changed take void * hold arbitrary data, can done:

typedef void (*callback_func)(int, void * data); extern int set_callback(callback_func cb); 
set_callback([](int x, void * data) {      myclass &self = *reinterpret_cast<myclass *>(data);      // code ...      self.prom.set_value(true); }); 

otherwise, you'd have have static objects or similar.


Comments