歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++11之std::function和std::bind

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

日期:2017/3/1 9:08:37   编辑:Linux編程

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;
}

Copyright © Linux教程網 All Rights Reserved