zoukankan      html  css  js  c++  java
  • std::function

    类模版std::function是一种通用、多态的函数封装。
    可调用对象的包装器,它最重要的功能是实现延时调用。
    std::function对象是对C++中现有的可调用实体的一种类型安全的封装。
    1、绑定普通函数
    void func(void)
    {
        std::cout << __FUNCTION__ << std::endl;
    }
    
    std::function<void(void)> fr1 = func;
    fr1();
    2、绑定一个类的静态成员函数
    class Foo
    {
    public:
        static int foo_func(int a)
        {
            std::cout << __FUNCTION__ << "(" << a << ") ->: ";
            return a;
        }
    };
    std::function<int(int)> fr2 = Foo::foo_func;
    std::cout << fr2(123) << std::endl;
    3、重载()函数
    class Bar
    {
    public:
        int operator()(int a)
        {
            std::cout << __FUNCTION__ << "(" << a << ") ->: ";
            return a;
        }
    };
    Bar bar;
    std::cout << bar(123) << std::endl;
    4、回调函数
    void call_when_even(int x, const std::function<void(int)>& f)
    {
        if (!(x & 1))  //x % 2 == 0
        {
            f(x);
        }
    }
    void output(int x)
    {
        std::cout << x << " ";
    }
    call_when_even(i, output);
  • 相关阅读:
    常见问题
    查询
    多对多关系
    prototype & __proto__
    new operator
    用户
    express.Router
    Express 应用生成器
    LeanCloud
    npm常用命令
  • 原文地址:https://www.cnblogs.com/osbreak/p/11087398.html
Copyright © 2011-2022 走看看