参考自:https://www.cnblogs.com/lsgxeva/p/7787438.html
https://www.cnblogs.com/nzbbody/p/3489573.html
在C++中,可调用实体主要包括函数,函数指针,函数引用,可以隐式转换为函数指定的对象,或者实现了opetator()的对象(即C++98中的functor)。C++11中,新增加了一个std::function对象,std::function对象是对C++中现有的可调用实体的一种类型安全的包裹,比如:std::function<Layer*()>代表一个可调用对象,接收0个参数,返回Layer*。
#include <iostream> #include <map> #include <functional> using namespace std; // 普通函数 int add(int i, int j) { return i + j; } // lambda表达式 auto mod = [](int i, int j){return i % j; }; // 函数对象类 struct divide { int operator() (int denominator, int divisor){ return denominator / divisor; } }; int main() { map<char, function<int(int, int)>> binops = { { '+', add }, { '-', minus<int>() }, { '*', [](int i, int j){return i - j; } }, { '/', divide() }, { '%', mod }, }; cout << binops['+'](10, 5) << endl; cout << binops['-'](10, 5) << endl; cout << binops['*'](10, 5) << endl; cout << binops['/'](10, 5) << endl; cout << binops['%'](10, 5) << endl; return 0; }通过std::function的包裹,我们可以像传递普通的对象一样来传递可调用实体,这样就很好解决了类型安全的问题。