C++11 function

#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最大的用处就是在实现函数回调,使用者需要注意,它不能被用来检查相等或者不相等.
原文地址:https://www.cnblogs.com/kex1n/p/7072124.html