#include <iostream> #include <functional> #include <vector> using namespace std; // c type global function int c_func(int a, int b) { return a + b; } //function object class functor { public: int operator() (int a, int b) { return a + b; } }; int main() { //old use way typedef int (*F)(int, int); F f = c_func; cout<<f(1,2)<<endl; functor ft; cout<<ft(1,2)<<endl; ///////////////////////////////////////////// std::function< int (int, int) > myfunc; myfunc = c_func; cout<<myfunc(3,4)<<endl; myfunc = ft; cout<<myfunc(3,4)<<endl; //lambda myfunc = [](int a, int b) { return a + b;}; cout<<myfunc(3, 4)<<endl; ////////////////////////////////////////////// std::vector<std::function<int (int, int)> > v; v.push_back(c_func); v.push_back(ft); v.push_back([](int a, int b) { return a + b;}); for (const auto& e : v) { cout<<e(10, 10)<<endl; } return 0; }
C++中,可調用實體主要包括函數,函數指針,函數引用,可以隱式轉換為函數指定的對象,或者實現了opetator()的對象(即C++98中的functor)。C++11中,新增加了一個std::function對象,std::function對象是對C++中現有的可調用實體的一種類型安全的包裹(我們知道像函數指針這類可調用實體,是類型不安全的).
- (1)關於可調用實體轉換為std::function對象需要遵守以下兩條原則:
a. 轉換后的std::function對象的參數能轉換為可調用實體的參數
b. 可調用實體的返回值能轉換為std::function對象的返回值(這里注意,所有的可調用實體的返回值都與返回void的std::function對象的返回值兼容)。 - (2)std::function對象可以refer to滿足(1)中條件的任意可調用實體
- (3)std::function object最大的用處就是在實現函數回調,使用者需要注意,它不能被用來檢查相等或者不相等.