标签:相等 public 指针 函数 strong str 回调 使用 最大的
#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++中现有的可调用实体的一种类型安全的包裹(我们知道像函数指针这类可调用实体,是类型不安全的).
标签:相等 public 指针 函数 strong str 回调 使用 最大的
原文地址:http://www.cnblogs.com/kex1n/p/7072124.html