【问题标题】:Passing lambdas as C function pointers将 lambdas 作为 C 函数指针传递
【发布时间】:2021-05-01 02:52:36
【问题描述】:

我正在开发一个将无捕获 lambda 传递给 C 库的 C++ 类。我想删除一些样板文件,并且 lambdas 都非常相似(它们找到一个类的实例并调用所有采用单个 int 参数的不同方法)。我创建了一个模板函数:

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;
  });
}

当我编译这个时,我得到一个关于 lambda 试图隐式捕获 callback 的错误,这是有道理的。我想知道,因为我在一个模板中,并且 createEditLineCommandDescriptor 是用常量地址成员函数参数调用的,有没有办法让编译器在实例化模板时生成 lambda 而无需尝试捕获C++11中的参数?

【问题讨论】:

    标签: c++ templates lambda


    【解决方案1】:

    您可以制作callback模板参数,并在调用createEditLineCommandDescriptor时指定模板参数而不是传递函数参数。例如

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

    【讨论】:

    • 可能是((&amp;foo)-&gt;* -> (foo.*(除非Foo 重载operator&amp;)。
    猜你喜欢
    • 2016-06-28
    • 2021-10-05
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 2010-12-22
    相关资源
    最近更新 更多