报名网站辽宁省建设银行,科技网站配色,国内seo排名分析主要针对百度,做奖状的网站基类定义虚函数#xff0c;子类实现虚函数#xff0c;使用基类指针指向子类对象#xff0c;从而实现多态#xff0c;functionbind可以使没有任何关系的各种类对象及其行为以一种相同的行为表现出来#xff0c;类似多态#xff0c;高于多态#xff0c;这里没有继承、没有…基类定义虚函数子类实现虚函数使用基类指针指向子类对象从而实现多态functionbind可以使没有任何关系的各种类对象及其行为以一种相同的行为表现出来类似多态高于多态这里没有继承、没有指针、没有虚函数、松耦合… 将某类对象及其行为包装为模板类function的实例对象或以模板函数bind将某类对象及其行为包装为模板类function的实例对象定义包含模板类function的实例对象的Base类使用Base类可以表现为多态性
元组tuple存储标准库function实例对象 包装各种类对象及其成员函数 、解包元组对象链接点击这里 目录 1、代码中的模板类func及模板函数bind_f是为了理解标准库里的工具库functional的包装类function及函数bind本人所写2、代码使用标准库的functionbind 1、代码中的模板类func及模板函数bind_f是为了理解标准库里的工具库的包装类function及函数bind本人所写
#include iostream
#include tuple //元组//std::make_index_sequence ( )//std::tuple_sizedecltype(args)::value//A类
struct A{void f(int a, int b, double c) { std:: cout A: a b c a b c \n; }
};
//B类
struct B{void f(int a, int b) { std:: cout B: a b a b \n; }
};//func模板类
templatetypename T,typename...Args
class func{
private:T a; //T类型对象void (T::*f)(Args...); //T类型对象的成员函数std::tupleArgs... args; //保存可变参数//保存T类型对象的成员函数的参数templatesize_t...index //tuple解包//c14void tuple_unpack(std::index_sequenceindex... ){ (a.*f)( std::getindex(args)... ); }
public: func( const T a, void(T::*f)(Args...),Args...args ):a(a),f(f), args(args...) { } //参数为对象、成员函数指针及可变参数的构造函数 void operator()(){ //重载 () tuple_unpack( std::make_index_sequence std::tuple_sizedecltype(args)::value ( ) );}
};//bind_f模板函数// 返回func模板类对象
templatetypename T,typename...Args
funcT,Args... bind_f(const T a, void(T::*f)(Args...),Args...args ){ return funcT,Args...(a, f,args... ); //构造一个func对象
} //包含模板类func实例对象的Base类
struct Base{templatetypename Tvoid fun(T t){ t(); }
};int main(int, char *[] )
{Base base;A a;B b;//多态性//但A类、B类没有任何关系base.fun( bind_f(a, A::f,5,9,1.23 ) ); // A类base.fun( bind_f(b, B::f,5,6 ) ); // B类return 0;
}
2、代码使用标准库的functionbind
#include iostream
#include functional //function bind//工具类标准库//A类
struct A{void f(int a, int b, double c) { std:: cout A: a b c a b c \n; }
};
//B类
struct B{void f(int a, int b) { std:: cout B: a b a b \n; }
};//Base类
struct Base{templatetypename Tvoid fun(T t){ t(); }
};int main(int, char *[] )
{Base base;A a;B b;//多态性//但A类、B类没有任何关系base.fun( std::bind(A::f,a, 5,9,1.23 ) ); // A类base.fun( std::bind(B::f,b, 5,6) ); // B类return 0;
}