2012-08-05 59 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