给一个闭包作为«类方法指针»?

时间:2014-12-19 07:39:27

标签: c++ c++11 lambda closures function-pointers

好的,这应该很简单,基本上下面的例子应该有效(至少要编译)

class Foo {
public:
    void DoNothing( void(Foo::*funcptr)() ){}
    void CallDoNothing();
};

void Foo::CallDoNothing(){
    auto closure = [this](){};
    DoNothing(closure);
}

int main(){
    return 0;
}

但由于某种原因会触发编译错误

test.cpp: In member function ‘void Foo::CallDoNothing()’:
test.cpp:9:19: error: no matching function for call to ‘Foo::DoNothing(Foo::CallDoNothing()::__lambda0&)’
  DoNothing(closure);
                   ^
test.cpp:9:19: note: candidate is:
test.cpp:3:7: note: void Foo::DoNothing(void (Foo::*)())
  void DoNothing( void(Foo::*funcptr)() ){}
       ^
test.cpp:3:7: note:   no known conversion for argument 1 from ‘Foo::CallDoNothing()::__lambda0’ to ‘void (Foo::*)()’

我甚至已经尝试过投射:DoNothing(reinterpret_cast< void(Foo::*funcptr)() >(closure));DoNothing(( void(Foo::*funcptr)() )closure);,加上一些变体 - 这些都只是触发了编译错误!

1 个答案:

答案 0 :(得分:2)

为什么你认为lambda函数可以分配给成员函数指针? lambda函数属于某种匿名类型。只有当它具有空捕获时,它才可以分配给函数指针,但即使这与示例中的成员函数指针不兼容。

您可以使用std::function<void ()>或使DoNothing成为模板功能。