是否可以将参数绑定(bind)到成员函数调用,然后单独绑定(bind)目标对象?
我试图实现的是一个辅助函数,它接收一个带有任意参数的函数作为参数,然后对集合中的所有项目执行它。
void SomeType::Work(UINT a, UINT b, UINT c)
{
//do something
}
template<typename Function, class Container>
void Execute(const Function& fn, const Container& collection)
{
for(auto& item : collection)
{
auto bound = std::bind(fn, &item);
bound();
}
}
void Test()
{
//eg. container = vector of SomeType
auto fn = std::bind(&Sometype::Work, 10, 20, 30);
Execute(fn, container);
}
由于功能中的一些错误而失败:
error C2064: term does not evaluate to a function taking 3 arguments
最终指向:
see reference to function template instantiation 'void Execute<std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall SomeType::* )(UINT,UINT,UINT),void,SomeType,UINT,UINT,UINT>,UINT &,UINT &,UINT &>>(const Function &)' being compiled
with
[
Function=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall SomeType::* )(UINT,UINT,UINT),void,SomeType,UINT,UINT,UINT>,UINT &,UINT &,UINT &>
]
我通过传递一个 lambda 来解决它,该 lambda 捕获所需的值并对传递给它的对象执行所需的函数。我仍然想知道以这种方式绑定(bind)函数是否有任何好处,我只是做错了,或者它是否不可行。
最佳答案
在绑定(bind)成员函数Sometype::Work()
时,你应该为第二次绑定(bind)时绑定(bind)的目标对象留一个占位符。
试试这个:
using namespace std::placeholders;
auto fn = std::bind(&Sometype::Work, _1, 10, 20, 30);
~~
关于c++ - 使用 std::bind 分别绑定(bind)参数和对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38827144/