使用std::function包装类成员函数

std::function

std::function是一个函数包装器模板,最早来自boost库,对应其boost::function函数包装器。在c++11中,std::function能包装任何类型的可调用元素,可以包装:函数、函数指针、类成员函数指针或任意类型的函数对象。

包装类成员函数示例

#include <functional>
#include <iostream>

class Publisher
{
public:
    void RegistFunc(std::function<void(int, int)> func) {
        std::cout << "Publisher RegistFunc()" << std::endl;
        func(1, 2);
    }
};

class Subscriber
{
public:
    Subscriber(int a, int b) : a_(a), b_(b) {}

    virtual ~Subscriber(){};

    void Notify(int a, int b) {
        std::cout << "Notify: a = " << a << ", b = " << b << std::endl;
        this->a_ = a;
        this->b_ = b;
    }

    void Start() {
        std::cout << "Subscriber Start()" << std::endl;
        Publisher pub;
        std::function<void(int,int)> func = std::bind(&Subscriber::Notify, this, std::placeholders::_1, std::placeholders::_2);
        pub.RegistFunc(func);
    }

    void show() {
        std::cout << "show: a = " << a_ << ", b = " << b_ << std::endl;
    }

private:
    int a_;
    int b_;
};

int main(int argc, char* argv[])
{
    std::cout << "main start" << std::endl;
    Subscriber sb(5, 6);
    sb.show();
    sb.Start();
    sb.show();
    std::cout << "main end" << std::endl;
}

执行结果

main start
show: a = 5, b = 6
Subscriber Start()
Publisher RegistFunc()
Notify: a = 1, b = 2
show: a = 1, b = 2
main end

std::bind时,可以通过占位符,改变参数顺序。

//修改为
std::bind(&Subscriber::Notify, this, std::placeholders::_2, std::placeholders::_1);

执行结果

main start
show: a = 5, b = 6
Subscriber Start()
Publisher RegistFunc()
Notify: a = 2, b = 1
show: a = 2, b = 1
main end
  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值