TypeSelection 实用的类型选择

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
//
template<int v>
struct Int2Type{};
//
template<bool flag,typename T,typename U>
struct Select
{
 typedef T Result;
};
template<typename T,typename U>
struct Select<false,T,U>
{
 typedef U Result;
};
//
template<typename T,bool isPolymorphic>
class NifyContainer
{
 typedef typename Select<isPolymorphic,T*,T>::Result ValueType;//true为引用,false为指针
 vector<ValueType> MyList;//多态的要存指针,非多态要存对象(有效率)
 void Print(ValueType pObj, Int2Type<true>)
 {
  cout<<"添加了一个多态指针:"<<*pObj<<endl;
 }
 void Print(ValueType pObj, Int2Type<false>)
 {
  cout<<"添加了一个非多态对象:"<<pObj<<endl;
 }
 void DeleteItem(Int2Type<true>)//多态的要主动析构
 {
  int n = 0;
  vector<ValueType>::iterator it = MyList.begin(),itend = MyList.end();
  for(;it != itend; it++){
   cout<<"析构值:";
   Print(*it,Int2Type<isPolymorphic>());
   delete *it;
   cout<<"析构了第:"<<++n<<"次"<<endl;
  }
 }
 void DeleteItem(Int2Type<false>)//
 {
  cout<<"只装有对象的VECTOR不用析构"<<endl;
 }
public:
 void AddList(ValueType p)
 {
  Print(p,Int2Type<isPolymorphic>());
  MyList.push_back(p);
 }
 ~NifyContainer()
 {
  cout<<"-----------------------------开始清理内存"<<endl;
  DeleteItem(Int2Type<isPolymorphic>());
  MyList.clear();
  cout<<"-----------------------------清理内存结束"<<endl;
 }
};
int _tmain(int argc, char *argv[])
{
 NifyContainer<int,true>* Ni = new NifyContainer<int,true>;
 Ni->AddList(new int(5));
 Ni->AddList(new int(15));
 Ni->AddList(new int(35));
 NifyContainer<float,false>* Ni2 = new NifyContainer<float,false>;
 float ff = 3.4f;
 Ni2->AddList(ff);
 delete Ni;
 delete Ni2;
 system("PAUSE");
 return EXIT_SUCCESS;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值