VS2013 std::function with member function [duplicate]

这一生的挚爱 提交于 2019-12-11 09:41:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!