我目前正在使用一個枚舉映射到一個Base *數組。每個派生類型由枚舉給出一個索引。異構指針容器
enum DerivedType {
DERIVED_TYPE_1 = 0,
DERIVED_TYPE_2,
...
NUM_DERIVED_TYPES
};
class Base {
};
class Derived1 : public Base {
static const DerivedType type;
};
const DerivedType Derived1::type = DERIVED_TYPE_1;
class Derived2 : public Base {
static const DerivedType type;
};
const DerivedType Derived2::type = DERIVED_TYPE_2;
class Container {
Base* obs[NUM_DERIVED_TYPES];
template<class T>
void addOb(T* ob) {
obs[T::type] = ob;
}
template<class T>
T* getOb() {
return (T*) obs[T::type];
}
Base* getOb(DerivedType type) {
return obs[type];
}
};
由於每個派生類型的索引是在編譯時已知的,是有辦法具有非模板getOb(DerivedType type)
返回正確DerivedN指針,可能通過在一個int仰視類型名稱 - >類型名稱地圖?或者有更好的方法來實現這種類型的模式?此外,將每個Derived類型添加到任何數據結構將其指定爲其索引值是很好的。基本上,我需要一個靜態異構指針容器,它可以通過類型或索引來訪問,同時返回正確的派生*。我猜測Boost有些東西可行,但我還沒有找到它。
感謝您的任何幫助。
非常好,正是我在找的,謝謝。我做的一個改進是讓map自動從vector中填充:'typedef bm :: fold,bm :: push_back >>::: type Container;' –
Ryan
2011-05-15 02:54:29
謝謝,很高興幫助:-) – 2011-05-15 07:56:05