Search code examples
c++templates

extracting template types from struct


I have the simple tag struct

template<typename...>
struct tag{};

and a class

template <typename T, typename ...Args>
class Impl {
  public:
    T func(Args...);
};

Is it possible to have a conversion/specialization or something, to allow to write Impl<int, tag<int, double>> and have it converted to Impl<int, int, double> a helper struct would work too.

I have tried using template template parameters but this seems to work the other way around, i.e. putting the types into a template. I also tried using a type alias inside tag:

template<typename... Args>
struct tag {
    using types = Args;
};

but this is not allowed.


Solution

  • The declarations declare different types, but if you don't need them to be the same type, you could add a specialization that inherits from Impl<T, Args...>:

    template <class T, class... Args>
    class Impl<T, tag<Args...>> : public Impl<T, Args...> {
    public:
        using type = Impl<T, Args...>;
        using Impl<T, Args...>::Impl;
        using Impl<T, Args...>::operator=;
    };
    

    Impl<T, tag<Args...>> will now have the member functions of Impl<T, Args...> available. Also Impl<T, tag<Args...>>::type will be available for declarations:

    int main() {
        Impl<int, tag<int, double>> a;
        Impl<int, tag<int, double>>::type b;
        
        a.func(2, 3.14159);
        b.func(2, 3.14159);
    }
    

    Demo