模板参数重新声明

Nee*_*asu 6 c++ templates

这就是我想要实现的目标.leaf组件将继承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;
  ...
};
Run Code Online (Sandbox Code Playgroud)

但问题是模板参数被重新声明.而且我不能将第二个移到第一个之上,因为第二个继承了第一个.

错误:使用2个模板参数重新声明
注意:上一个声明'模板类Component'使用了1个模板参数

Joh*_*erg 3

这可以编译,据我了解,它可以做你喜欢的事情:

#include <vector>

class NoneT {};

template <typename ParentT,typename ChildT=NoneT>
class Component: public Component<ParentT>{
  protected:
    typedef std::vector<ChildT*> CollectionT;
};
Run Code Online (Sandbox Code Playgroud)

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

someT将会有ParentComponentT并且someT2将会有CollectionT

编辑:

回答下面的评论/问题:typename ChildT=noneT意味着默认ChildT值为noneT. 因此,如果没有给出第二个模板参数,noneT则将使用该类型。

然后,专业化定义该单参数版本的类内容。

编辑2:

因为我从聊天中知道您使用 Component 作为基类,所以我建议不要使用类似的东西

class myclass: public Component<Section, Line>
Run Code Online (Sandbox Code Playgroud)

你可以使用多重继承

class myclass: public ParentComponent<Section>, CollectionComponent<Line>
Run Code Online (Sandbox Code Playgroud)

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

template <typename ChildT>
class CollectionComponent {
  protected:
    typedef std::vector<ChildT*> CollectionT;
};
Run Code Online (Sandbox Code Playgroud)