C++11新特性,bind,基于对象

function/bind:


std::function:
☞std::function<R(T1, T2, ..., TN)> 

☞这是一个模板实现的函数对象类,它可以包装其它任意的函数对象,而被包装的函数对象具有类型为T1,T2,…,TN的参数,其返回值为R类型

☞function 对象的最大用处在于实现函数回调



bind:
☞bind是这样一种机制,它可以预先把指定可调用实体的某些参数绑定到已有的变量,产生一个新的可调用实体
☞绑定的参数的个数不受限制
☞绑定的具体哪些参数也不受限制,由用户指定
☞bind预先绑定的参数需要传具体的变量或值进去,是pass-by-value(值传递)
☞对于不事先绑定的参数,需要传std::placeholders进去,从_1开始,依次递增
☞bind的返回值是可调用实体,可以直接赋给std::function对象



面向对象  vs  基于对象:
☞面向对象的三大特点(封装,继承,多态)缺一不可。
☞通常“基于对象”是使用对象,但是并不利用现有的对象模板产生新的对象类型,继而产生新的对象,即“基于对象”没有继承的特点。
☞“面向对象”和“基于对象”都实现了“封装”的概念,但是面向对象实现了“继承和多态”,而“基于对象”没有实现这些。

                                                               继承(面向对象)  vs  组合(基于对象)


// bind 返回一个新的可调用实体
// function 对象实现函数回调
#include<iostream>
#include<functional>
using namespace std;
using std::function;
//using std::placeholders;  // namespace ‘std::placeholders’ not allowed in using-declaration
using namespace std::placeholders;
int func(int x,int y)
{
        return x+y;
}
class A
{
        public:
                int func(int x,int y)
                {
                        return x+y;
                }
};

int main()
{
        // function<int(int,int)> test1  = bind(func,10,placeholders::_1);
// 只有一个占位符,意思传参只要传一个,所以形参不能是两个,和原函数没关系
        function<int(int)> test1  = bind(func,10,placeholders::_1);
        cout<<test1(20)<<endl;

        A a;
        function<int(int)> test2 = bind(&A::func,&a,30,_1);  
// 前面声明,就不用写placeholders
        cout<<test2(40)<<endl;

        function<int(int,int)> test3 = func;
        cout<<test3(10,20)<<endl;

        //function<int(const A&,int,int)> test4 = &A::func;  
        function<int(A&,int,int)> test4 = &A::func;  
// 今天脑子犯抽,const成员对象只能调用const修饰的成员函数
        cout<<test4(a,10,20)<<endl;
        return 0;
}





原文地址:https://www.cnblogs.com/meihao1203/p/9368363.html