c++ - 使用 std::bind 分别绑定(bind)参数和对象实例

标签 c++ c++11 std stdbind

是否可以将参数绑定(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);
                                     ~~

LIVE

关于c++ - 使用 std::bind 分别绑定(bind)参数和对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38827144/

相关文章:

c++ - 在qt creator中调试时如何访问字符串变量的完整值?

C++ 和类对象名称

c++ - rcpp包创建符号找不到错误

c++ - 重载元组索引运算符 - C++

c++ - std::thread 错误(线程不是 std 的成员)

c++ - `std::bitset::reference` 赋值运算符?

C++ : Is Namespaces definition allowed before '#include <files>' .

c++ - 混合别名和模板特化

c++ - std::set_intersection 和迭代器

C++ 变量在传递给函数时丢失值