Get the template class out of control in C ++

Regarding the legacy code that I was asked to work with, I came across a concept that I don’t understand. Searching in SO and googling did not help, therefore, this question.

There is a template class that looks like this:

template<int Index_t, int Kind_t, ProtocolType Prot_t, class Protocol> class CommandHandlerGeneric : private CommandHandlerGeneric<Index_t-1, Kind_t, Prot_t, Protocol> { public: CommandHandlerGeneric(Protocol& Shared, CmdHandlerBase** Cont) : CommandHandlerGeneric<Index_t-1, Kind_t, Prot_t, Protocol>(Shared, Cont) {} }; 

The CmdHandlerBase class is not a template class that exists elsewhere in a different header. Following the definition above, there is a macro that looks like this:

 #define REGISTER_COMMAND_HANDLER_BASE(CmdIndex, CmdType, CmdKind, ProtType) \ template<class Protocol> \ class CommandHandlerGeneric<CmdIndex, CmdKind, ProtType, Protocol> : private CommandHandlerGeneric<CmdIndex-1, CmdKind, ProtType, Protocol> \ { \ CmdType m_Cmd;\ public: \ CommandHandlerGeneric(Protocol& Shared, CmdHandlerBase** Cont) : \ m_Cmd(Shared), \ CommandHandlerGeneric<CmdIndex-1, CmdKind, ProtType, Protocol>(Shared, Cont) \ { Cont[CmdIndex] = &m_Cmd; } \ }; 

It appears that the specified macro partially specializes in the CommandHandlerGeneric class CommandHandlerGeneric . It's right? What is the rationale for withdrawing a private lesson from oneself?

+6
source share
2 answers

I can’t do anything from your specific example, but overall it’s a recursive template. For Index_t = x must be a specialization that completes the recursion.

The second ingredient here is private inheritance, which can be considered as a form of composition . In combination with a recursive template, you can use this to create a class of variable sizes, such as a vector of a certain size.

+3
source

Note:

 template<int Index_t, int Kind_t, ProtocolType Prot_t, class Protocol> class CommandHandlerGeneric : private CommandHandlerGeneric<Index_t-1, Kind_t, Prot_t, Protocol> 

The first template parameter has been changed. This is not the same class. A class template is not a complete class until all parameters are specified.

Indeed, it is illegal to inherit from the same class template and pass the same set of parameters, but it is not.

+2
source

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


All Articles