天天看点

C++11:std::function

在C++中,可调用实体主要包括:函数、函数指针、函数引用、可以隐式转换为函数指定的对象,或者实现了opetator()的对象。

#include <iostream>
#include <functional>   //std::cout
using namespace std;

void func(void)
{//普通全局函数
    cout << __func__ << endl;
}

class Foo
{
public:
    static int foo_func(int a)
    {//类中静态函数
        cout << __func__ << "(" << a << ") ->: ";
        return a;
    }
};

class Bar
{
public:
    int operator()(int a)
    {//仿函数
        cout << __func__ << "(" << a << ") ->: ";
        return a;
    }
};

int main()
{
    //绑定一个普通函数
    function< void(void) > f1 = func;
    f1();

    //绑定类中的静态函数
    function< int(int) > f2 = Foo::foo_func;
    cout << f2(111) << endl;

    //绑定一个仿函数
    Bar obj;
    f2 = obj;
    cout << f2(222) << endl;

    return 0;
}      

继续阅读