【发布时间】:2016-08-08 10:43:09
【问题描述】:
是否可以将参数绑定到成员函数调用,然后单独绑定目标对象?
我试图实现的是一个辅助函数,它接收一个带有任意参数的函数作为参数,然后在集合中的所有项目上执行它。
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 表达式捕获所需的值并在传递给它的对象上执行所需的函数。我仍然想知道这种方式的绑定函数是否有任何作用,我只是做错了,或者它是否不可行。
【问题讨论】:
-
Sometype::Work的定义在哪里? -
它只是一个接受最初定义的参数的函数。在上面添加了一个示例定义。
-
你绑定绑定了吗?我发现 lambda 更清晰,递归怪癖更少。