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

      

      

      

  • 相关阅读:
    PAT——1069. 微博转发抽奖
    PAT——1068. 万绿丛中一点红
    PAT——1066. 图像过滤
    PAT——1065. 单身狗
    PAT——1064. 朋友数
    PAT——1063. 计算谱半径
    PAT——1062. 最简分数
    PAT——1061. 判断题
    PAT——1060. 爱丁顿数
    PAT——1059. C语言竞赛
  • 原文地址:https://www.cnblogs.com/jiayayao/p/6139201.html
Copyright © 2011-2022 走看看