使用std::bind分别绑定参数和对象实例

Using std::bind to bind parameters and object instance separately

本文关键字:参数 对象 绑定 实例 std bind 使用      更新时间:2023-10-16

是否可以将参数绑定到成员函数调用,然后单独绑定目标对象?

我试图实现的是一个助手函数,它接收一个带有任意参数的函数作为参数,然后在集合中的所有项上执行它。

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()时,您应该为目标对象保留一个占位符,该占位符将在第二次绑定时绑定。

试试这个:

using namespace std::placeholders;
auto fn = std::bind(&Sometype::Work, _1, 10, 20, 30);
                                     ~~

实时

听起来您只是想将一个函数(带有特定参数(应用于集合。

我看不出这与使用具有特定函数的std::for_each有什么不同。

void Test()
{
    //eg. container = vector of SomeType
    auto fn1 = [/*whatever*/](const container_value_type& obj) { 
        Sometype::Work(10, 20, 30, obj);
    }
    auto fn2 = [/*whatever*/](const container_value_type& obj) { 
        Sometype::Work(40, 50, 60, obj);
    }
    std::for_each(container.begin(), container.end(), fn1);
    std::for_each(container.begin(), container.end(), fn2);
}