2012-08-05 53 views
6

這就是我想要實現的。葉組件繼承Component<ParentT>,其他人將繼承Component<ParentT, ChildT>模板參數重新聲明

template <typename T> 
class Component{ 
    protected: 
    typedef Component<T> ParentComponentT; 
    ... 
}; 

template <typename ParentT, typename ChildT> 
class Component: public Component<ParentT>{ 
    protected: 
    typedef std::vector<ChildT*> CollectionT; 
    ... 
}; 

但問題是模板參數入門重新聲明。我不能將第二個繼承第一個,因爲第二個繼承了第一個。

error: redeclared with 2 template parameter(s)
note: previous declaration ‘template class Component’ used 1 template parameter(s)

+1

目前忽略可變參數模板,模板具有固定數量的參數;一個Component <>'不能同時具有一個和兩個參數。這看起來像一個[XY問題](http://meta.stackexchange.com/q/66377/166663) - 你究竟想要完成什麼? – ildjarn 2012-08-05 06:31:31

+0

那麼建模它的好方法是什麼? '組件'? – 2012-08-05 06:32:40

+0

這取決於 - 爲什麼你要基地和孩子有相同的名字?給他們不同的類型名稱,你沒有問題。 – ildjarn 2012-08-05 06:33:12

回答

3

這編譯而據我理解做你喜歡什麼:

#include <vector> 

class NoneT {}; 

template <typename ParentT,typename ChildT=NoneT> 
class Component: public Component<ParentT>{ 
    protected: 
    typedef std::vector<ChildT*> CollectionT; 
}; 

專業化面向NoneT

template<> 
template<typename T> 
class Component<T,NoneT>{ 
protected: 
    typedef Component<T> ParentComponentT; 
}; 

int main(){ 
    typedef Component<double> someT; 
    typedef Component<double,int> someT2; 
    typedef Component<double,void> someT3; 
} 

someT將有ParentComponentTsomeT2將有CollectionT

編輯:

回答評論/下面的問題:typename ChildT=noneT即表示默認ChildTnoneT。因此,如果沒有給出第二個模板參數,將使用noneT類型。

專門化然後定義該單參數版本的類內容。

EDIT2:

因爲我從你使用組件作爲基類的聊天知道的,我建議,而不是像

class myclass: public Component<Section, Line> 

可以使用多重繼承

class myclass: public ParentComponent<Section>, CollectionComponent<Line> 

template <typename T> 
class ParentComponent{ 
    protected: 
    typedef Component<T> ParentComponentT; 
}; 

template <typename ChildT> 
class CollectionComponent { 
    protected: 
    typedef std::vector<ChildT*> CollectionT; 
}; 
+0

爲什麼'ChildT = NoteT'或'ChildT = void'如果是第一個模板?您在 – 2012-08-05 07:47:21

+0

的第二個中專門說明了 – 2012-08-05 07:50:10

+0

如果沒有給出第二個模板參數,它會轉到第二個模板版本。爲什麼它會查找默認參數? – 2012-08-05 07:52:00