Search code examples
c++templatesc++17typename

C++ - Get typename of a template where that class is used as another template


I would like to get the typename of a class template from another class that use a tamplate based on the first class.

I have wrote a class like so:

template<typename T>
class class_a {
  ...
}

I would like to do something that:

template<class class_a>
class class_b {
  std::vector<class_a.T> arr;
  ...
}

Solution

  • The easiest way to do this is to have your templates "cooperate" with each other, and for class_a to "help" the other template:

    template<typename T>
    class class_a {
    
    public:
       typename T type_t;
    };
    

    And then:

    template<class class_a>
    class class_b {
      std::vector<typename class_a::type_t> arr;
      ...
    };
    

    You will find this to be a pretty much standard design pattern in the C++ library itself. Most C++ containers, for example, define value_type, so if we changed the typedef to value_type:

    template<typename T>
    class class_a {
    
    public:
       typename T value_type;
    };
    

    And then:

    template<class class_a>
    class class_b {
      std::vector<typename class_a::value_type> arr;
      ...
    };
    

    Then if your class_b were to be instantiated using a std::list, for example:

    class_b<std::list<char>> b;
    

    Then your arr will end up being std::vector<char>.

    An alternative that does not require this "cooperation" would be to use a helper template with specialization, in order to avoid having to explicitly declare a typedef alias. However this is the simplest solution unless you have some specific reason not to do things this way.