1. 程式人生 > >std::function , std::bind 用法

std::function , std::bind 用法

轉:https://blog.csdn.net/liukang325/article/details/53668046

關於std::function 的用法: 
其實就可以理解成函式指標 
1. 儲存自由函式

void printA(int a)
{
    cout<<a<<endl;
}

std::function<void(int a)> func;
func = printA;
func(2);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 儲存lambda表示式
std::function<void()> func_1 = [](){cout<<"hello world"<<endl;};
func_1();
  • 1
  • 2
  1. 儲存成員函式
struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { cout << num_+i << '\n'; }
    int num_;
};

// 儲存成員函式
std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
Foo foo(2);
f_add_display(foo, 1);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在實際使用中都用 auto 關鍵字來代替std::function… 這一長串了。


關於std::bind 的用法: 
看一系列的文字,不如看一段程式碼理解的快

#include <iostream>
using namespace std;
class A
{
public:
    void fun_3(int k,int m)
    {
        cout<<k<<" "<<m<<endl;
    }
};

void fun(int x,int y,int z)
{
    cout<<x<<"  "<<y<<"  "<<z<<endl;
}

void fun_2(int &a,int &b)
{
    a++;
    b++;
    cout<<a<<"  "<<b<<endl;
}

int main(int argc, const char * argv[])
{
    auto f1 = std::bind(fun,1,2,3); //表示繫結函式 fun 的第一,二,三個引數值為: 1 2 3
    f1(); //print:1  2  3

    auto f2 = std::bind(fun, placeholders::_1,placeholders::_2,3);
    //表示繫結函式 fun 的第三個引數為 3,而fun 的第一,二個引數分別有呼叫 f2 的第一,二個引數指定
    f2(1,2);//print:1  2  3

    auto f3 = std::bind(fun,placeholders::_2,placeholders::_1,3);
    //表示繫結函式 fun 的第三個引數為 3,而fun 的第一,二個引數分別有呼叫 f3 的第二,一個引數指定
    //注意: f2  和  f3 的區別。
    f3(1,2);//print:2  1  3


    int n = 2;
    int m = 3;

    auto f4 = std::bind(fun_2, n,placeholders::_1);
    f4(m); //print:3  4

    cout<<m<<endl;//print:4  說明:bind對於不事先繫結的引數,通過std::placeholders傳遞的引數是通過引用傳遞的
    cout<<n<<endl;//print:2  說明:bind對於預先繫結的函式引數是通過值傳遞的


    A a;
    auto f5 = std::bind(&A::fun_3, a,placeholders::_1,placeholders::_2);
    f5(10,20);//print:10 20

    std::function<void(int,int)> fc = std::bind(&A::fun_3, a,std::placeholders::_1,std::placeholders::_2);
    fc(10,20);//print:10 20

    return 0;
}