2021年4月30日星期五

Passing lambdas as C function pointers

I'm working on a C++ class that passes captureless lambdas to a C library. I'd like to remove some boilerplate, and the lambdas are all very similar (they find an instance of a class and invoke different methods that all take a single int parameter). I created a template function:

typedef unsigned char (Foo::*FooMemPtr)(int ch);    template<typename Fn>  tuple<const char*, const char*, Fn> createEditLineCommandDescriptor(const char* command, const char* helpText, const FooMemPtr callback) {    return make_tuple(command, helpText, [] (EditLine*, int ch) {      Foo foo;      ((&foo)->*callback)('a');      return ch;    });  }  

When I compile this I get an error about the lambda trying to implicitly capture callback, which makes sense. I'm wondering, since I'm in a template, and createEditLineCommandDescriptor is called with constant address-of-member-function parameters, is there any way to have the compiler generate the lambda when it's instantiating the template without trying to capture the parameter in C++11?

https://stackoverflow.com/questions/67342473/passing-lambdas-as-c-function-pointers May 01, 2021 at 10:52AM

没有评论:

发表评论