#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;
}
Type Selection 类型选择
最新推荐文章于 2024-07-31 15:55:00 发布