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;
}

原文链接: https://www.cnblogs.com/yaoyu126/p/12419299.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    std::function学习

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/333646

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午9:16
下一篇 2023年3月1日 下午9:17

相关推荐