C++ 以«形式给出一个闭包;类方法指针»;?

C++ 以«形式给出一个闭包;类方法指针»;?,c++,c++11,lambda,closures,function-pointers,C++,C++11,Lambda,Closures,Function Pointers,好的,这应该很简单,基本上下面的例子应该是有效的(至少要编译): 但由于某种原因,这会触发编译错误 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: 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(closure))
DoNothing((void(Foo::*funcptr)()闭包),加上一些变体-这些都触发了编译错误

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


您可以使用
std::function
或使
DoNothing
成为模板函数。

带有捕获的lambda无法转换为函数指针,更不用说成员函数指针了。@user657267好吧,如果确实如此,这非常令人伤心……好吧,那么我如何声明接受闭包的参数呢(即,捕获局部变量的lambda)?
std::function
我这么想是因为没有闭包的lambda可以由编译器隐式地转换为简单的函数指针。接下来我们问自己:闭包和这个简单的lambda有什么区别?接下来我们记得类函数指针不同于通常的指针,因为它们隐式地接受«this»作为第一个参数。因此,显然,闭包只能铸造到«class method pointer»上。这是一个推论:如果您知道只有捕获为空的lambda函数才能被分配到函数指针上,并且语言没有为捕获为lambda定义任何内容,我发现假设存在一个作为捕获的lambda与成员函数指针之间的关系。这在语义层面上听起来很合理,但编译器必须遵循语言定义。因为这并没有说明,我不明白为什么你应该假设它是有效的。逻辑参数和语言标准有时非常不同:-)嗯,我不知道语言标准没有为闭包定义任何强制转换,这就是为什么我试图在实际程序中编写一个类似lisp的函数,最后问了这个问题☺@嗨,安琪尔,你可以在isocpp.org上查阅最新的标准草案。它不是很可读,但可以作为参考。你也可以在这个论坛的一个论坛问为什么转换被省略,也许你甚至可以说服他们考虑它的未来标准。
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::*)()’