I'm wrapping a C library and want to allow using the parameter list of the callback's function pointer to determine how to cast the void*
on the other side of the asynchronous call. The problem is I can't figure out how to get access to the templatized callback from within the lambda trampoline. Below is example code with a comment where the compiler error is occurring, but the invalid code should give the idea of what I'm going for.
// Hypothetical asynchronous C library call
typedef void (*future_cb)(void* data);
void call_in_the_future(future_cb cb, void* data) {
cb(data);
}
struct Mine { /* For sake of the example */ };
struct Wrapper {
Wrapper() : ptr_(nullptr) { }
template <typename DataType>
void run(void (*cb)(Wrapper* wrap, DataType other), DataType ptr) {
auto lcb = [](void* data) {
Wrapper* wrap = static_cast<Wrapper*>(data);
DataType other = static_cast<DataType>(wrap->ptr_);
/***** Compiler error here *****/
cb(wrap, other);
};
ptr_ = ptr;
// Call the hypothetical asynchronous C library function.
call_in_the_future(lcb, this);
}
void* ptr_;
};
// Looking to store each type and cast them for this callback.
static void wrapper_cb(Wrapper* wrap, Mine* me) { }
int main() {
Mine* me = new Mine();
Wrapper* wrap = new Wrapper();
wrap->run(wrapper_cb, me);
}
Here are the build errors:
main5.cc:19:7: error: variable 'cb' cannot be implicitly captured in a lambda with no capture-default specified
cb(wrap, other);
^
main5.cc:13:19: note: 'cb' declared here
void run(void (*cb)(Wrapper* wrap, DataType other), DataType ptr) {
^
main5.cc:14:16: note: lambda expression begins here
auto lcb = [](void* data) {
^
main5.cc:19:7: error: variable 'cb' cannot be implicitly captured in a lambda with no capture-default specified
cb(wrap, other);
^
main5.cc:37:9: note: in instantiation of function template specialization 'Wrapper::run<Mine *>' requested here
wrap->run(wrapper_cb, me);
^
main5.cc:13:19: note: 'cb' declared here
void run(void (*cb)(Wrapper* wrap, DataType other), DataType ptr) {
^
main5.cc:14:16: note: lambda expression begins here
auto lcb = [](void* data) {
^
2 errors generated.
EDIT: There's a compile error if I try to capture cb
in the lambda:
error: no matching function for call to 'call_in_the_future'
EDIT 2: To make it clear, I understand why these two build errors are happening. What I'm wondering is if there's a way around these issues so I can call cb
.