開(kāi)平做網(wǎng)站百度官方版
類(lèi)模板std::function是一種通用、多態(tài)的函數(shù)包裝。std::function的實(shí)例可以對(duì)任何可以調(diào)用的目標(biāo)實(shí)體進(jìn)行存儲(chǔ)、
復(fù)制和調(diào)用操作。這些目標(biāo)實(shí)體包括普通函數(shù)、Lambda表達(dá)式、函數(shù)指針、以及其他函數(shù)對(duì)象等。std::function對(duì)象是對(duì)
C++中現(xiàn)有的可調(diào)用實(shí)體的一種類(lèi)型安全的包裹(像函數(shù)指針這類(lèi)可調(diào)用實(shí)體,是類(lèi)型不安全的)
?? ?通常std::function是一個(gè)函數(shù)對(duì)象類(lèi),它包裝其它任意的函數(shù)對(duì)象,被包裝的函數(shù)對(duì)象具有類(lèi)型為T(mén)1,...Tn的n個(gè)參數(shù)
并且可返回一個(gè)可轉(zhuǎn)換到R類(lèi)型的值。std::function使用模板轉(zhuǎn)換構(gòu)造函數(shù)接收被包裝的函數(shù)對(duì)象。
?? ?準(zhǔn)確來(lái)說(shuō),可調(diào)用對(duì)象有如下幾種定義:
?? ?(1)是一個(gè)函數(shù)指針;
?? ?(2)是一個(gè)具有operator()成員函數(shù)的類(lèi)對(duì)象
?? ?(3)是一個(gè)可以被轉(zhuǎn)換為函數(shù)指針的類(lèi)對(duì)象
?? ?(4)是一個(gè)類(lèi)成員函數(shù)指針
#include<iostream>
#include<functional>
using namespace std;void func(int x)
{cout << "func name:" << __FUNCTION__ << endl;cout << "x=" << x << endl;
}
class Foo
{
public:static int foo_func(int x){cout << "func name:" << __FUNCTION__ << endl;cout << "x=" << x << endl;return x;}
};
class Bar
{
public:int operator()(int x){cout << "func name:" << __FUNCTION__ << endl;cout << "x=" << x << endl;return x;}
};
int main()
{int x = 10;//綁定一個(gè)普通函數(shù)std::function<void(int)> fr1 = func;fr1(x);//綁定一個(gè)類(lèi)的靜態(tài)成員函數(shù)std::function<int(int)> fr2 = Foo::foo_func;cout << fr2(x) << endl;Bar bar;fr2 = bar;std::cout << fr2(x) << endl;return 0;
}