问题
I'm trying to use std::function with member functions like this:
struct Foo
{
void bar(int) const { /* ... */ }
};
//later on
std::function<void(const Foo&, int)> fun = &Foo::bar;
This works under GCC 4.8.1 but fails to compile under VS2013 with the following error:
error C2664: 'void std::_Func_class<_Ret,const Foo &,int>::_Set(std::_Func_base<_Ret,const Foo &,int> *)' :
cannot convert argument 1 from '_Myimpl *' to 'std::_Func_base<_Ret,const Foo &,int> *'
It looks to me like a bug in VS but maybe I'm not seeing something? Is there a way to workaround it (without external libs like boost)?
Edit: I forgot "const" in bar signature. But this still doesn't work in VS.
回答1:
std::function
is required to accept pointers to member functions (definition of INVOKE
).
The simplest workaround is to use std::mem_fn
instead, or wrap the constructor argument with std::mem_fn
:
std::function<void(const Foo&, int)> fun = std::mem_fn(&Foo::bar);
来源:https://stackoverflow.com/questions/23778883/vs2013-stdfunction-with-member-function