std::function学习

使用std::function绑定

以下源内容来自于《深入应用C++11 代码优化与工程级应用》1.5.2 可调用对象包装器——std::function

std::function是可调用对象的包装器。它是一个类模板,可以容纳除了类成员(函数)指针之外的所有可调用对象。通过指定它的模板参数,它可以用统一的方式处理函数函数对象函数指针,并允许保存和延迟执行它们。

#include <iostream>
#include <functional>
using namespace std;

// 普通函数
void func(void)
{
    cout << __FUNCTION__ << endl;
}

// 静态函数
struct Foo
{
    static int foo_func(int a)
    {
        cout << __FUNCTION__ << "(" << a << ")->:";
        return a;
    }
};

// 仿函数
struct Bar
{
    int operator()(int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};

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

    // 绑定一个类的静态成员函数
    std::function<int(int)> fr2 = Foo::foo_func;
    std::cout << fr2(123) << std::endl;

    // 绑定一个仿函数
    Bar bar;
    fr2 = bar;
    std::cout << fr2(234) << std::endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/yaoyu126/p/12419299.html