天天看點

回調函數在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;
}           

繼續閱讀