天天看點

C++11之std::function和std::bind

轉載自:https://www.cnblogs.com/jiayayao/p/6139201.html    多謝版主

std::function是可調用對象的包裝器,它最重要的功能是實作延時調用:

#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::function<int(int)> fr2,那麼fr2就可以代表傳回值和參數表相同的一類函數。可以看出fr2儲存了指代的函數,可以在之後的程式過程中調用。這種用法在實際程式設計中是很常見的。

  std::bind用來将可調用對象與其參數一起進行綁定。綁定後可以使用std::function進行儲存,并延遲到我們需要的時候調用:

  (1) 将可調用對象與其參數綁定成一個仿函數;

  (2) 可綁定部分參數。

  在綁定部分參數的時候,通過使用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;
}