使用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;
    }
}

posted @ 2022-03-06 09:47  陈小蓝  阅读(169)  评论(0编辑  收藏  举报