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

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

#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) 將可調用對象與其參數綁定成一個仿函數;spa

  (2) 可綁定部分參數。code

  在綁定部分參數的時候,經過使用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;
}
相關文章
相關標籤/搜索