classClassMemberFunc { public: staticintstaticAdd(int a, int b) { std::cout << "static member func" << std::endl; return a + b; }; intinstanceAdd(int a, int b) { std::cout << "instance member func" << std::endl; return a + b; }; };
classClassFunctor { public: intoperator()(int a, int b) { std::cout << "functor" << std::endl; return a + b; }; };
intfuncAdd(int a, int b) { std::cout << "function" << std::endl; return a + b; }
intmain(int argc, constchar * argv[]) { std::map<int, std::function<int(int,int)>> funcMap; int (*fp)(int, int) = funcAdd; auto lambdaAdd = [](int a, int b)->int{ std::cout << "lambda" << std::endl; return a + b; }; ClassMemberFunc cmf; ClassFunctor cf; auto bind = std::bind(&ClassMemberFunc::instanceAdd, cmf, std::placeholders::_1, std::placeholders::_2); funcMap[1] = funcAdd; funcMap[2] = fp; funcMap[3] = lambdaAdd; funcMap[4] = ClassMemberFunc::staticAdd; funcMap[5] = bind; funcMap[6] = cf; for(int i = 1 ; i <= 6 ; i++) { std::cout<< "index " << i << ": "; funcMap[i](i,1); } }
输出结果如下:
1 2 3 4 5 6
index 1: function index 2: function index 3: lambda index 4: static member func index 5: instance member func index 6: functor