Search code examples
c++dependent-typetemplate-templates

Use template from dependent type


How to call a template with a template parameter, when the template is inside a template type parameter:

template<template<class> class Template, class T>
struct MakeType
{
    using type = Template<T>;
};

template<class Policy>
struct Blah
{
    using type = MakeType< /*A non-instantiated template member in Policy*/, int>::type;
};

For example, Policy could have a template member ArrayType:

class ExamplePolicy
{
    template<class T>
    using ArrayType = std::vector<T>;
};

How do I call MakeType from Blah with the template Policy::ArrayType as Template.

Calling MakeType directly works well:

static_assert(std::is_same_v<std::vector<int>, MakeType<std::vector, int>::type>);

Would compile


Solution

  • Does this solve your problem?

    // -*- compile-command: "g++ SO.cpp"; -*-
    #include <vector>
    
    template <template <class> class Template, class T>
    struct MakeType
    {
      using type = Template<T>;
    };
    
    template <class Policy>
    struct Blah
    {
      using type = typename MakeType<Policy::template ArrayType, int>::type;
    
      type foo()
      {
        return type();
      }
    };
    
    struct ExamplePolicy
    {
      template <class T>
      using ArrayType = std::vector<T>;
    };
    
    int main()
    {
      Blah<ExamplePolicy> blah;
    
      auto tmp = blah.foo();
    }