使用std::function和std::bind实现函数回调

std::function

作为c++11新增的内容,std::function的实例可以对任何可调用对象实体进行存储、复制、和调用。
其实就是一个对所有可调用对象的封装,通过一套方法调用一切。
可调用对象包括:

  • 普通函数
  • 函数指针
  • Lambda表达式
  • 仿函数对象
  • 类静态函数
  • 类成员函数
  • 其他函数对象

**注意:**std::function的实例将可调用对象封装成一个新的对象,所以不能判断两个std::function是否是同一个函数的封装。

std::bind

std::bind与std::function不同,std::function是一个类模板,而std::bind则是一个函数,它可以将可调用对象及其参数进行封装,也可以对参数顺序进行重新组织,甚至改变其参数个数。

code

#include <iostream>
#include <functional>

extern "C" {
    int func1(int a)
    {
        std::cout << __FUNCDNAME__ << std::endl;
        return a;
    }

    int func2(int a, int b)
    {
        std::cout << __FUNCDNAME__ << std::endl;
        return a + b;
    }

    int callFunc(std::function<int(int)> f, int a)
    {
        std::cout << __FUNCDNAME__ << std::endl;
        return f(a);
    }

    int main()
    {
        std::function<int(int)> f1 = func1;
        std::cout << f1(1) << std::endl;

        std::function<int(int, int)> f2 = func2;
        std::cout << f2(1, 2) << std::endl;

        std::function<int(int)> f3 = std::bind(func2, std::placeholders::_1, 2);
        std::cout << f3(1) << std::endl;

        std::cout << callFunc(func1, 2) << std::endl;
        std::cout << callFunc(f3, 2) << std::endl;
        std::cin.ignore();
        return 0;
    }
}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ango_Cango

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值