C++:创建映射到枚举的某种类型的对象

Kri*_*ris 2 c++

考虑以下代码示例:

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 ];
    }

}
Run Code Online (Sandbox Code Playgroud)

我认为用文字来描述我的真实系统目前的功能更好。

现在实际上我有更多的类从 base 派生,大约有 15 个。

  • 我是否有所有从 Base 派生的类的重复代码?在 switch 语句中为它们添加一行,以及从数组中获取它们的附加辅助函数?

  • 有没有办法自动化这个?

sth*_*sth 5

沿着这些路线的东西应该工作:

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];
}
Run Code Online (Sandbox Code Playgroud)

然后就可以使用cont.Add<A>()来创建A对象,并cont.Get<B>()接收B对象。

如果这实际上是一个好主意取决于您为什么要这样做......