開平做網(wǎng)站百度官方版
類模板std::function是一種通用、多態(tài)的函數(shù)包裝。std::function的實例可以對任何可以調(diào)用的目標(biāo)實體進行存儲、
復(fù)制和調(diào)用操作。這些目標(biāo)實體包括普通函數(shù)、Lambda表達式、函數(shù)指針、以及其他函數(shù)對象等。std::function對象是對
C++中現(xiàn)有的可調(diào)用實體的一種類型安全的包裹(像函數(shù)指針這類可調(diào)用實體,是類型不安全的)
?? ?通常std::function是一個函數(shù)對象類,它包裝其它任意的函數(shù)對象,被包裝的函數(shù)對象具有類型為T1,...Tn的n個參數(shù)
并且可返回一個可轉(zhuǎn)換到R類型的值。std::function使用模板轉(zhuǎn)換構(gòu)造函數(shù)接收被包裝的函數(shù)對象。
?? ?準(zhǔn)確來說,可調(diào)用對象有如下幾種定義:
?? ?(1)是一個函數(shù)指針;
?? ?(2)是一個具有operator()成員函數(shù)的類對象
?? ?(3)是一個可以被轉(zhuǎn)換為函數(shù)指針的類對象
?? ?(4)是一個類成員函數(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;//綁定一個普通函數(shù)std::function<void(int)> fr1 = func;fr1(x);//綁定一個類的靜態(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;
}