2011-10-19 76 views
1

我有持有對象的幾個向量類來訪問類的不同成員:如何通過使用特徵模式

struct ComponentA 
{ 
public: 
    methodA1(); 
    float data1; 
    ... 
}; 
struct ComponentB 
{ 
    ... 
}; 
struct ComponentC 
{ 
    ... 
}; 
struct ComponentD 
{ 
    ... 
}; 

class Assembly 
{ 
    vector<ComponentA> As; 
    vector<ComponentB> Bs; 
    vector<ComponentC> Cs; 
    vector<ComponentD> Ds; 
}; 

我想用特徵和定義可返回參考這樣的成員函數:

template< int T > 
struct ComponentTraits; 

template<> 
ComponentTraits<TYPEA> 
{ 
    typedef vector<ComponentA> data_type; 
} 
.... 
template< int T > 
ComponentTraits<T>::data_type getComp(const Assembly & myassy) 
{ 
    ... 
} 

使得呼叫

getComp<TYPEA>(thisassy) 

將參考返回作爲這樣我可以在矢量層級操縱和訪問每個組件對象方法和數據:

getComp<TYPEA>(thisassy).push_back(newcomponentA); 
getComp<TYPEA>(thisassy).back().methodA1(); 
getComp<TYPEA>(thisassy).front().data1 = 5.0; 

感謝,

和田

回答

1

性狀都不會做你想要的這裏。 C++缺乏需要反省的支持來說,「讓我成爲類型爲Y的類X的第一個成員。」此外,特徵旨在用於「告訴我更多關於X型」的操作。

模板專業化,可用於這一點,但他們將大量的工作:

template<class T> 
T& getComp<T>(Assembly& assy); 

template<> 
ComponentA& getComp<ComponentA>(Assembly& assy) 
{ return assy.As; 
} 

template<> 
ComponentB& getComp<ComponentB>(Assembly& assy) 
{ return assy.Bs; 
} 

template<> 
ComponentC& getComp<ComponentC>(Assembly& assy) 
{ return assy.Cs; 
} 

template<> 
ComponentD& getComp<ComponentD>(Assembly& assy) 
{ return assy.Ds; 
} 

或更短:

template<class T> 
T& getComp<T>(Assembly& assy); 

#define SpecializeGetComp(T, field) template<> \ 
T& getComp<T>(Assembly& assy) { return assy.field; } 

SpecializeGetComp(ComponentA, As) 
SpecializeGetComp(ComponentB, Bs) 
SpecializeGetComp(ComponentC, Cs) 
SpecializeGetComp(ComponentD, Ds) 

您可能還需要在類型串讀了(章3)在Alexandrescu的書Modern C++ Design。你可能能夠以類似Factory的模式使用它們,但這不僅僅是一個SO答案。

+0

Mike,感謝您指出C++中缺乏反省。我現在正在閱讀類型列表,希望能夠學習一些關於模板的技巧。 – user966004

相關問題