我想写一个以模板类做为参数的模板,,可惜。。。没成功。
1.从模板参数到模板:这个简单:
//类A是一个模板
template<class T>
class A{
};
//类B,想使用类A的模板
template <class T>
class B{
A<T> a;
};
2.从模板到模板参数:
类B想使用类A里面的模板参数:
template <class T>
class A{
typedef T T1;
};
template <class A>
class B{
A::T1 a_t1;
};
实例:
// templatestudy.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <cstdlib>#include <iostream>#include <algorithm>#include <functional>//谓词 using namespace std;template <typename _M1_T>struct LESS:public binary_function<_M1_T,_M1_T,bool>{//接受2个参数bool operator()(const _M1_T& x,const _M1_T&y) const{return x<y;} };template <class T>struct LESS_THAN:public unary_function<T,bool>{T arg2;//构造函数explicit LESS_THAN(const T& x):arg2(x){}//接受一个参数的()操作bool operator()(const T& x) const {return x<arg2;} } ;//把函数对象模板类中的第二个参数进行约束://有两个问题要解决://第一:要获取函数对象模板的类型参数。//第二:对此类型的值进行约束template<class BinOp>class _binder2nd:public unary_function<typename BinOp::first_argument_type,typename BinOp::result_type>{protected:BinOp op;typename BinOp::second_argument_type arg2;public:_binder2nd(const BinOp & x,const typename BinOp::second_argument_type&v):op(x),arg2(v){}result_type operator()(const argument_type&x) const{return op(x,arg2);}};//约束第二个参数int main(int argc, char *argv[]){int a=5;LESS_THAN<int> less_10(10);less_10(a);system("PAUSE");return EXIT_SUCCESS;}
使用方法:
bind2nd(less<int>(),7);
意思是把less<int>()函数对象,的第二个函数参数绑定为7.