Search code examples
c++templatesc++17variadic-templates

Passing template template parameters


Let's say we have a class called TypeCollection that holds a packed template of types:

template<typename ...Types>
class TypeCollection {};

And if we have a class that templates a TypeCollection you would need to do something a little like this:

template<template<typename ...> class Collection, typename ...Types>
class CollectionHandler {};

Which would be instantiated like so:

CollectionHandler<TypeCollecion, A, B, C>

This isn't great since we have to pass the types A B and C twice for template deduction. My question is if there is a way to do this without having to pass the types twice:

CollectionHandler<TypeCollecion<A, B, C>>

However I cant seem to get this to work. I tried a couple things and I realized that you cant pass a templated class as a parameter:

CollectionHandler<TypeCollecion<A, B, C>>  // Error: Template argument for template template parameter must be a class template or type alias template

Is there a way to instantiate CollectionHandler without having to pass the types twice? I experimented with tuples to hide the parameters but I couldn't get that to work either.

Thanks for your help!


Solution

  • Flip your CollectionHandler declaration around to dissect the TypeCollection through template specialization:

    template <class TypeCollection>
    class CollectionHandler;
    
    template <class... Types>
    class CollectionHandler<TypeCollection<Types...>> { };