function与bind

function是一个可调用对象包装器,可以用来存储函数对象。bind函数允许绑定指定位置的参数,参数个数可以小于函数本身参数个数。bind函数返回的对象可以用function接收,并且可以被其调用。

int add_num(int a, int b, int c, int d)
{
    return a + b + c + d;
}

int main()
{
    auto tmp_fun = add_num;
    cout << tmp_fun(1,2,3,4) << endl;

    std::function<int(int,int,int,int)> tmp_fun1 = add_num;
    cout << tmp_fun1(2, 3, 4, 5) << endl;

    using namespace std::placeholders; //命名空间

    auto f = std::bind(add_num, 1, _1, _2, 3);//占位符的位置随意,即占位符前后都可以有参数
    cout << f(1, 2, 3, 4) << endl; // 1+1+2+3

    std::function<int(int, int, int)> fuc = std::bind(add2078, 2, _1, 2, 3);//参数个数小于函数本身参数个数

    cout << fuc(1, 2, 3);

    return 0;
}

对于有成员函数的情况来说,代码会稍微复杂些,如下所示:

 

#define reg_test_func(num) \
    _func[num] = std::bind(&Test2071::on_test_##num, this, _1); //需要有取地址符号&,还要指明是哪个类的以及this参数

class Test2071
{
public:
    typedef std::function<void(int)> Function;

public:
    void init() {
        reg_test_func(1);
        reg_test_func(2);
    }
    void on_test_1(int i);
    void on_test_2(int i);

    void exec_test() {
        for (auto &it : _func) {
            it.second(1);
        }
    }

private:
    std::map<int, Function> _func;
};

void Test2071::on_test_1(int i)
{
    cout << "test1: " << i << endl;
}

void Test2071::on_test_2(int i)
{
    cout << "test2: " << i << endl;
}

int main()
{
    Test2071 tst;
    tst.init();
    tst.exec_test();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值