// test-object-create-template.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <boost\ptr_container\ptr_vector.hpp>
#include <iostream>
#include <windows.h>
using namespace std;
class BASE : boost::noncopyable
{
public:
virtual ~BASE() {}
};
class T1 : public BASE{
public:
T1() {
cout << "T1 created\n";
}
virtual ~T1() {
cout << "T1 destroied\n";
}
};
class T2 : public BASE{
public:
T2() {
cout << "T2 created\n";
}
virtual ~T2() {
cout << "T2 destroied\n";
}
};
class Factory {
public:
boost::ptr_vector<BASE> ptr_set;
Factory() {
}
template<class T>
T* get() {
static T* g_ptr = NULL;
if( !g_ptr ) {
g_ptr = new T();
ptr_set.push_back( g_ptr );
}
return g_ptr;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
{
boost::ptr_vector<BASE> ptr_set;
ptr_set.push_back( new T1);
ptr_set.push_back( new T2);
}
{
Factory f;
T1* t1 = f.get<T1>();
T2* t2 = f.get<T2>();
T1* t3 = f.get<T1>();
assert( f.ptr_set.size() == 2);
}
//delete t1;
//delete t2;
Sleep(1000);
return 0;
}
用模板简化factory的实现
最新推荐文章于 2017-05-04 17:36:12 发布