回调函数在C++11中的另一种写法

C++11之前写回调函数的时候,一般都是通过 
typedef void CALLBACK (*func)();

方式来声明具有某种参数类型、返回值类型的通用函数指针。上面例子声明了一个返回值是void,无参数的函数指针。

其中,返回值和参数可以使用 boost::any 或者 auto进行泛型指代。

C++11引入了

#include <functional>

包含2个函数std::function 和 std::bind。

其中std::function学名是可调用对象的包装器,作用和上面

typedef void CALLBACK (*func)();

差不多,都是指代一组具有参数个数和类型,以及返回值相同的函数。举例如下:

#include "stdafx.h"
#include<iostream>// std::cout
#include<functional>// std::function

void func(void)
{
    std::cout << __FUNCTION__ << std::endl;
}

class Foo
{
public:
    static int foo_func(int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};

class Bar
{
public:
    int operator() (int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};

int main()
{
    // 绑定普通函数
    std::function<void(void)> fr1 = func;
    fr1();

    // 绑定类的静态成员函数,需要加上类作用域符号
    std::function<int(int)> fr2 = Foo::foo_func;
    std::cout << fr2(100) << std::endl;

    // 绑定仿函数
    Bar bar;
    fr2 = bar;
    std::cout << fr2(200) << std::endl;

    return 0;
}

其中std::bind将可调用对象与实参进行绑定,绑定后可以赋值给std::function对象上,并且可以通过占位符std::placeholders::决定空位参数(即绑定时尚未赋值的参数)具体位置。举例如下:

#include "stdafx.h"
#include<iostream>// std::cout
#include<functional>// std::function

class A
{
public:
    int i_ = 0; // C++11允许非静态(non-static)数据成员在其声明处(在其所属类内部)进行初始化

    void output(int x, int y)
    {
        std::cout << x << "" << y << std::endl;
    }

};

int main()
{
    A a;
    // 绑定成员函数,保存为仿函数
    std::function<void(int, int)> fr = std::bind(&A::output, &a, std::placeholders::_1, std::placeholders::_2);
    // 调用成员函数
    fr(1, 2);

    // 绑定成员变量
    std::function<int&(void)> fr2 = std::bind(&A::i_, &a);
    fr2() = 100;// 对成员变量进行赋值
    std::cout << a.i_ << std::endl;


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值