c++ 以模板类作为参数的模板

我想写一个以模板类做为参数的模板,,可惜。。。没成功。

 

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.


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值