【发布时间】:2015-02-18 03:05:31
【问题描述】:
好的,应该很简单,基本上下面的例子应该可以工作(至少可以编译):
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);,以及对此的一些变体——这些都只是触发了编译错误!
【问题讨论】:
-
无法将带有捕获的 Lambda 转换为函数指针,更不用说成员函数指针了。
-
@user657267 好吧,如果确实如此,那就太可悲了……好吧,那我如何声明一个接受闭包的参数(即捕获局部变量的 lambda)?
-
std::function<void()>
标签: c++ c++11 lambda closures function-pointers