std::function
作爲c++11新增的內容,std::function的實例可以對任何可調用對象實體進行存儲、複製、和調用。
其實就是一個對所有可調用對象的封裝,通過一套方法調用一切。
可調用對象包括:
- 普通函數
- 函數指針
- Lambda表達式
- 仿函數對象
- 類靜態函數
- 類成員函數
- 其他函數對象
**注意:**std::function的實例將可調用對象封裝成一個新的對象,所以不能判斷兩個std::function是否是同一個函數的封裝。
std::bind
std::bind與std::function不同,std::function是一個類模板,而std::bind則是一個函數,它可以將可調用對象及其參數進行封裝,也可以對參數順序進行重新組織,甚至改變其參數個數。
code
#include <iostream>
#include <functional>
extern "C" {
int func1(int a)
{
std::cout << __FUNCDNAME__ << std::endl;
return a;
}
int func2(int a, int b)
{
std::cout << __FUNCDNAME__ << std::endl;
return a + b;
}
int callFunc(std::function<int(int)> f, int a)
{
std::cout << __FUNCDNAME__ << std::endl;
return f(a);
}
int main()
{
std::function<int(int)> f1 = func1;
std::cout << f1(1) << std::endl;
std::function<int(int, int)> f2 = func2;
std::cout << f2(1, 2) << std::endl;
std::function<int(int)> f3 = std::bind(func2, std::placeholders::_1, 2);
std::cout << f3(1) << std::endl;
std::cout << callFunc(func1, 2) << std::endl;
std::cout << callFunc(f3, 2) << std::endl;
std::cin.ignore();
return 0;
}
}