考虑以下代码示例:
class Base;
class A; class B; class C; //A, B and C are inherited from Base
enum TypeID
{
TYPE_A = 0, TYPE_B, TYPE_C, TYPE_MAX;
}
class SomeContainer
{
private Base* objects[ TYPE_MAX ];
public void Add( TypeID what )
{
if( objects[ what ] ) return;
switch( what )
{
case TYPE_A: objects[ TYPE_A ] = (Base*) new A;
case TYPE_B: objects[ TYPE_B ] = (Base*) new B;
case TYPE_C: objects[ TYPE_C ] = (Base*) new C;
default: printf( "Invalid type\n" ); return NULL;
}
}
public A* GetA()
{
return (A*) objects[ TYPE_A ];
}
public B* GetB()
{
return (B*) objects[ TYPE_B ];
}
public C* GetC()
{
return (C*) objects[ TYPE_C ];
}
}
我认为描述我的真实系统当前的功能比文字更好。
现在实际上我有更多的从基类派生的类,大约有 15 个。
沿着这些思路的东西应该有效:
class A; class B; class C;
template<class T>
struct type_index;
template<>
struct type_index<A> { static const size_t index = 0; };
template<>
struct type_index<B> { static const size_t index = 1; };
template<>
struct type_index<C> { static const size_t index = 2; };
template<class T>
public Base* Add() {
size_t index = type_index<T>::index;
if( !objects[index] )
objects[index] = new T;
return objects[index];
}
template<class T>
public T* Get() {
return (T*) objects[type_index<T>::index];
}
然后你可以使用cont.Add<A>()
来创建A
对象,以及cont.Get<B>()
接收B
object.
如果这实际上是一个好主意取决于你为什么要尝试这样做......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)