首页 > 解决方案 > Template specialization and inheritance template class from other template class

问题描述

I have some questions about next code:

template<typename T>
class Base;

template<typename T, typename P>
class Base<T(P)> {

};

template<typename T>
class Derived;

template<typename T, typename P>
class Derived<T(P)> : public Base<T(P)> {

};
  1. Class specialization Derived<T(P)> inherits from class template<typename T> class Base or from class template<typename T, typename P> class Base<T(P)>?

  2. What the name of when I'm binding template parameters T and P of class specialization Derived<T(P)> with template parameter T of class Base.

标签: c++templatesinheritancespecialization

解决方案


  1. A class instantiated from the template Derived<T(P)> inherits from the class instantiated from Base<T(P)>. Since the type T(P) matches your Base partial specialization, that template will be used to instantiate the class to inherit from.

  2. It's just called inheritance. There's nothing special going on there. You're just instantiating the template Base with the type T(P) and inheriting from the resulting class.


Base<T(P)> will get instantiated when Derived<T(P)> gets instantiated, so Derived<void(int)> inherits from Base<void(int)>. Both of those instantiations will go through the same set of rules to figure out which template to use to instantiate that class.

You may be getting confused thinking that T(P) is some special template thing. It is not. It's just the type "function that returns T and takes a single argument of type P". Granted, types like that don't come up much outside of templates, but they're perfectly legal other places. i.e.

using FuncType = void(int);

// These two declarations are exactly the same
void doAThing(FuncType* callback);
void doAThing(void(*callback)(int));

推荐阅读