先說函數指針:
函數指針區別於指針函數,指針函數,就是一個普通的函數,只是返回值是指針;函數指針,我們可以把一個函數的地址通過指針來存放,這個指針就是函數指針變量,簡稱函數指針。
int * func(int a,int b) //指針函數,定義了一個具有兩個int型參數的函數,返回值是int型的指針。
int(*func)(int a,int b) //函數指針,定義了一個指向帶有兩個int型參數函數的指針。
通過*號是跟類型在一起還是跟函數名在一起的來區分是指針函數還是函數指針。
下邊進入正題,std::function std::bind
1. std::function
- std::function 是一個可調用對象包裝器,是一個類模板,可以容納除了類成員函數指針之外的所有可調用對象,它可以用統一的方式處理函數、函數對象、函數指針,並允許保存和延遲它們的執行。
- 定義格式:std::function<函數類型>。
- std::function可以取代函數指針的作用,因爲它可以延遲函數的執行,特別適合作爲回調函數使用。它比普通函數指針更加的靈活和便利。
2. std::bind
可將std::bind函數看作一個通用的函數適配器,它接受一個可調用對象,生成一個新的可調用對象來“適應”原對象的參數列表。
std::bind將可調用對象與其參數一起進行綁定,綁定後的結果可以使用std::function保存。std::bind主要有以下兩個作用:
class Func
{
public:
int sum;
Func()
{
sum = 2;
}
void func2(int bbb,int aaa,int numa, int numb, int numc, std::string name)
{
std::cout << numa << " " << numb << " " << numc << " " << name << endl;
}
void func4()
{
std::cout << "func4" << endl;
}
void func20(int a,int b)
{
}
void operator() (int a, int b)
{
std::cout << "Operator:" << sum << " " << a << " " << b << endl;
}
static void func6(int numa, int numb, int numc)
{
std::cout << numa << " " << numb << " " << numc << endl;
}
static void func5()
{
std::cout << "static func" << endl;
}
};
int main()
{
Func func;
std::function<void(int a,int b)> testFunc_1 = std::bind(&Func::func2, func, std::placeholders::_2, std::placeholders::_1,1,2, 3, "name");
testFunc_1(100, 200);
system("pause");
return 0;
}
輸出:
int main()
{
callFunc(std::bind(func1, std::placeholders::_1, std::placeholders::_2, 3));
callFunc(std::bind(func1, std::placeholders::_2, std::placeholders::_1, 3));
callFunc(std::bind(func1, std::placeholders::_2, 3, std::placeholders::_1));
callFunc(std::bind(Func::func6, std::placeholders::_1, std::placeholders::_2, 3));
callFunc(std::bind(&Func::func2, func, std::placeholders::_1, std::placeholders::_2, 3, "name"));
system("pause")
return 0
}
輸出:
int main()
{
Func func;
int sum = 10;
int resultInt = 0;
//全局或者靜態函數
std::cout << "全局或者靜態函數" << endl;
std::function<void()> testFunc = func3;
testFunc();
testFunc = Func::func5;
testFunc();
//類成員函數
std::cout << "類成員函數" << endl;
testFunc = std::bind(&Func::func2, func, 1, 2, 3, "name");
testFunc();
//Lambda表達式
std::cout << "Lambda表達式" << endl;
testFunc = [=, &resultInt](){std::cout << sum << endl; resultInt += 100; };
testFunc();
cout << "the reslutInt is " << resultInt << endl;
//仿函數
std::cout << "仿函數" << endl;
std::function<void(int a, int b)> abFunc = func;
abFunc(10, 20);
std::cout << resultInt << std::endl;
}
輸出: