如何在这里正确使用bind

How to use bind correctly here?

本文关键字:bind 在这里      更新时间:2023-10-16

我不知道绑定成员函数的正确语法。如果我有一个函数,它接受一个只有一个参数的函数,我如何传递一个对象给它?

在下面的例子中,传递函数的正确语法是什么?

#include <iostream>
#include <functional>
void caller(std::function<void(int)> f)
{
    f(42);
}
class foo
{
public:
    void f(int x)
    {
        std::cout<<x<<std::endl;
    }
};
int main()
{
    foo obj;
    caller(std::bind(&foo::f,obj));
    //^Wrong
} 

错误的是:

a.cpp: In function ‘int main()’:
a.cpp:18:34: error: could not convert ‘std::bind(_Func&&, _BoundArgs&& ...) [with _Func = void (foo::*)(int); _BoundArgs = {foo&}; typename std::_Bind_helper<std::__or_<std::is_integral<typename std::decay<_Tp>::type>, std::is_enum<typename std::decay<_Tp>::type> >::value, _Func, _BoundArgs ...>::type = std::_Bind<std::_Mem_fn<void (foo::*)(int)>(foo)>]((* & obj))’ from ‘std::_Bind_helper<false, void (foo::*)(int), foo&>::type {aka std::_Bind<std::_Mem_fn<void (foo::*)(int)>(foo)>}’ to ‘std::function<void(int)>’
     caller(std::bind(&foo::f,obj));

占位符为稍后绑定的实际参数创建一个"空格":

int main()
{
    foo obj;
    caller(std::bind(&foo::f, &obj, std::placeholders::_1));
    //                                   ^ placeholder
    //                        ^ address or even foo()
}

这些占位符需要正确地生成一个合适的签名,以便将std::bind结果绑定到std::function<void(int)>

你可能还想使用你的对象的地址,或者std::ref(这样它就不会被复制);这取决于您想要的语义。

成员函数有一个隐式的第一个参数,即this点。你需要给它发送作为指针;您还需要int参数的占位符。所以:

caller(std::bind(&foo::f, &obj, std::placeholders::_1));
//                        ^   ^^^^^^^^^^^^^^^^^^^^^^^

您需要使用占位符指定创建的函数对象接受参数:

std::bind(&foo::f,obj, std::placeholders::_1)