Home > Software design >  how to force instantiation of a template class used with a type alias
how to force instantiation of a template class used with a type alias

Time:07-02

I have a template class that takes a large number of template parameters.

This is an helper class that is used only on a predefined list of types. I use a type alias (using or typedef) so that the user does not get polluted with the template suff.

As the typelist is hardcoded, I would like to force the instantiation of the class T, but as the list is quite long I'd like to force instantiation without repeating all parameters.

How could I do that?

template <class... X>
class T {
};

// alias the type so that the user don't get mad with type list
using Z = T<int, bool, char, long
            /* possibly a long list of parameters*/ >;


// this works but needs to repeat all template arguments
template class T<int, bool, char, long>;

// how to force instantiation of T using Z?

CodePudding user response:

You can use specialization that allows to specify all template parameters as a single std::tuple:

#include <tuple>


template <class... X>
class T {};

template <class ...X>
class T<std::tuple<X...>> : public T<X...> {};

using types = std::tuple<int,bool,char,long>;

using Z = T<types>;

template class T<types>;

CodePudding user response:

As a workaround I used a macro...

#define MY_TYPE T<int,bool,char,long>

using Z = MY_TYPE;

template class MY_TYPE;

I'm still looking for a better solution...

  • Related