Search code examples
c++templatestemplate-templates

how can i use a template class as another class's typename?


I have a template class A:

template<typename T>
class A {
  void test(T & t) {
  }
};

now I want a derived template class B:

template <typename T>
class B {
  B() : a(new T<int>), b(new T<char>) {}
  T* a;
  T* b;
};

Is there any method i can implement this?


Solution

  • You should define T as a template template parameter, e.g.

    template<template<typename> class T>
    class B {
      B() : a(new T<int>), b(new T<char>) {}
      T<int>* a;
      T<char>* b;
    };
    

    Then you can specify other class template like A as the template argument such as B<A> b;.


    BTW: From C++17 you can use keyword typename for template template parameter declaration too. i.e.

    template<template<typename> typename T>
    class B {
      B() : a(new T<int>), b(new T<char>) {}
      T<int>* a;
      T<char>* b;
    };