C++11 std::bind

版权声明: https://blog.csdn.net/luoshabugui/article/details/80969130

一 声明

头文件<functional>

template< class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );

template< class R, class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );

参数说明:

f:A Function object, point to function or pointer to member.(函数对象,函数指针,函数引用, 指向成员函数指针或指向成员变量指针)

args: 要绑定的参数列表,每个参数可以是a value 或者 a placeholder。

作用:

bind生成 f 的转发调用包装器。调用该包装器相当于一一些绑定的参数调用f。实现延时调用。

二 举例

#include <iostream>
#include <functional>

struct Demo
{
void print (int a, int b){};
int a_;
};

int add(int& a, int& b)
{
    a++;
    b++;
    std::cout << "add " << a << " " << b << std::endl;
    return a + b;
}

int main()
{
    using namespace std::placeholders;
    {
        int a = 1;
        int b = 2;

        auto f = std::bind(add, a, _1); // 绑定普通函数, _1与调用时传入时相应位置参数对应
        a = 100;
        f(b); // output: add 2 3   说明bind时,预定参数值已经确定
    }

    {
        int a = 1;
        int b = 2;

        auto f = std::bind(add, a, _1);
        f(b);
        std::cout << " a: " << a << std::endl; // output: a: 1
        std::cout << " b: " << b << std::endl; // output: b: 3  其实还是值传递,原因是add函数参数是引用导致
    }

    Demo demo;
    auto f1 = std::bind(&Demo::print, &demo, _1, 10); // 绑定成员函数
    auto f2 = std::bind(&Demo::a_, &demo); // 绑定成员变量

    f1(20); // output: 20 10 1
    f2() = 20;
    f1(20); // output: 20 10 20
    system("pause");
    return 0;
}

三 注意

1、到 bind 的参数被复制或移动,而且决不按引用传递,除非用std::ref或者std::cref包装。

2、If fn is a pointer to member, the first argument expected by the returned function is an object of the class *fn is a member (or a reference to it, or a pointer to it).(当绑定的是成员函数或者成员变量时,第一个参数要是类实例、实例引用或者实例指针。即可以预绑定也可以占位后,调用时传递进来)。

猜你喜欢

转载自blog.csdn.net/luoshabugui/article/details/80969130
今日推荐