zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    AcWing356 次小生成树(lca)
    牛客 Rinne Loves Edges(dp)
    软件的生命周期和测试流程
    软件测试的学习经历回顾-第一天
    java List集合
    c#Socket通信
    c#线程2
    c#线程1
    c#Linq联合查询
    c#拓展方法
  • 原文地址:https://www.cnblogs.com/rayfloyd/p/14308757.html
Copyright © 2011-2022 走看看