Type Selection 类型选择

来源:互联网 发布:linux重启svn服务器 编辑:程序博客网 时间:2024/05/17 01:34

#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++){iterator
        delete *it;
        cout<<"析构了第:"<<++n<<"次"<<endl;
      }
      MyList.clear();
  }
  void DeleteItem(Int2Type<false>)//
  {
    cout<<"不用析构"<<endl;
  }
public:
  void AddList(ValueType p)
  {
    Print(p,Int2Type<isPolymorphic>());
    MyList.push_back(p);
  }
  ~NifyContainer()
  {
    cout<<"-----------------------------开始清理内存"<<endl;
  }
};
int main(int argc, char *argv[])
{
    NifyContainer<int,true> Ni;
    Ni.AddList(new int(5));
    NifyContainer<float,false> Ni2;
    float ff = 3.4f;
    Ni2.AddList(ff);
    system("PAUSE");
    return EXIT_SUCCESS;
}

原创粉丝点击