• c++11 中的函数回调方式


    #include <functional>
    #include <iostream>
    
    void print_num(int i);
    
    inline void print_num(int i)
    {
    std::cout << i << '
    ';
    }
    
    struct PrintNum {
    void operator()(int i) const
    {
    std::cout << i << '
    ';
    }
    };
    
    struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_ + i << '
    '; }
    int num_;
    };
    
    void main()
    {
    // store a free function // 存储自由函数
    std::function<void(int)> f_display = print_num;
    f_display(-9);
    
    // store a lambda //存储lambda表达式
    std::function<void()> f_display_42 = []() { print_num(42); };
    f_display_42();
    
    //store the result of a call to std::bind //存储std::bind 结果
    std::function<void()> f_display_31337 = std::bind(print_num, 31337);
    f_display_31337();
    
    // 类实例
    const Foo foo(314159);
    // store a call to a member function and object //存储类成员方法和类实例
    using std::placeholders::_1;
    std::function<void(int)> f_add_display2 = std::bind(&Foo::print_add, foo, _1);
    f_add_display2(2);
    
    // store a call to a member function and object ptr ////存储类成员方法和类实例指针
    std::function<void(int)> f_add_display3 = std::bind(&Foo::print_add, &foo, _1);
    f_add_display3(3);
    
    // store a call to a function object //存储结构体方法//仿函数
    std::function<void(int)> f_display_obj = PrintNum();
    f_display_obj(18);
    }
  • 相关阅读:
    实习第三十天
    实习第二十九天
    武汉第二十七天
    实习第二十六天
    实习第二十五天
    实习第二十四天
    python基础之核心风格
    1 Python入门
    对计算机的基础概念讨论
    一对多,父对象包含其他对象字段时创建的连接就是一对多连接
  • 原文地址:https://www.cnblogs.com/rayfloyd/p/14308757.html
Copyright © 2020-2023  润新知