Repeating Pattern Template

This is what I want to achieve. A sheet element inherits Component<ParentT> , others inherit 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; ... }; 

But the problem is that the template parameters are retrieved. and I cannot transfer the second above the first, because the second inherits the first.

error: updated with two template options


note: previous declaration 'template class Component used 1 template parameter

+6
source share
1 answer

This compiles, and as I understand it, does what you like:

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

Specialization for 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 will have a ParentComponentT and someT2 will be a CollectionT .

EDIT:

The answer to the comment / question is below: typename ChildT=noneT means that the default value of ChildT will be NoneT . So, if the argument of the second template is not specified, the NoneT type will be used.

The specialization then defines the contents of the class for this one-parameter version.

EDIT2:

Since I know from the chat that you are using Component as a base class, I suggest instead something like

 class myclass: public Component<Section, Line> 

you can use multiple inheritance

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

from

 template <typename T> class ParentComponent{ protected: typedef Component<T> ParentComponentT; }; template <typename ChildT> class CollectionComponent { protected: typedef std::vector<ChildT*> CollectionT; }; 
+3
source

Source: https://habr.com/ru/post/922142/


All Articles