zoukankan      html  css  js  c++  java
  • C++11之std::function和std::bind

      std::function是可调用对象的包装器,它最重要的功能是实现延时调用:

    #include "stdafx.h"
    #include<iostream>// std::cout
    #include<functional>// std::function
    
    void func(void)
    {
        std::cout << __FUNCTION__ << std::endl;
    }
    
    class Foo
    {
    public:
        static int foo_func(int a)
        {
            std::cout << __FUNCTION__ << "(" << a << ") ->: ";
            return a;
        }
    };
    
    class Bar
    {
    public:
        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(100) << std::endl;
    
        // 绑定仿函数
        Bar bar;
        fr2 = bar;
        std::cout << fr2(200) << std::endl;
    
        return 0;
    }

      由上边代码定义std::function<int(int)> fr2,那么fr2就可以代表返回值和参数表相同的一类函数。可以看出fr2保存了指代的函数,可以在之后的程序过程中调用。这种用法在实际编程中是很常见的。

      std::bind用来将可调用对象与其参数一起进行绑定。绑定后可以使用std::function进行保存,并延迟到我们需要的时候调用:

      (1) 将可调用对象与其参数绑定成一个仿函数;

      (2) 可绑定部分参数。

      在绑定部分参数的时候,通过使用std::placeholders来决定空位参数将会是调用发生时的第几个参数。

    #include "stdafx.h"
    #include<iostream>// std::cout
    #include<functional>// std::function
    
    class A
    {
    public:
        int i_ = 0; // C++11允许非静态(non-static)数据成员在其声明处(在其所属类内部)进行初始化
    
        void output(int x, int y)
        {
            std::cout << x << "" << y << std::endl;
        }
    
    };
    
    int main()
    {
        A a;
        // 绑定成员函数,保存为仿函数
        std::function<void(int, int)> fr = std::bind(&A::output, &a, std::placeholders::_1, std::placeholders::_2);
        // 调用成员函数
        fr(1, 2);
    
        // 绑定成员变量
        std::function<int&(void)> fr2 = std::bind(&A::i_, &a);
        fr2() = 100;// 对成员变量进行赋值
        std::cout << a.i_ << std::endl;
    
    
        return 0;
    }

      

      

      

  • 相关阅读:
    OpenCV 2.48配置
    win进入当前文件夹,启动当前文件夹的程序
    C++程序运行效率的10个简单方法
    银行国际清算业务平台架构
    股票证券交易系统架构分析与设计
    负载均衡|六种负载均衡算法
    Intelli IDEA快捷键(配合IdeaVim)(转)
    [易学易懂系列|golang语言|零基础|快速入门|(三)]
    [易学易懂系列|golang语言|零基础|快速入门|(二)]
    [易学易懂系列|golang语言|零基础|快速入门|(一)]
  • 原文地址:https://www.cnblogs.com/jiayayao/p/6139201.html
Copyright © 2011-2022 走看看