1

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?
OznOg
  • 4,440
  • 2
  • 26
  • 35
  • Assuming you want to do this because you want to implement the class template in a .cpp file, did you try creating a static instance of `Z` in _T.cpp_ ? – paolo Jul 01 '22 at 13:38
  • @paolo yes exactly, and no I did not try a static instance. – OznOg Jul 01 '22 at 13:39
  • I tried something with the static (actually, the meyer's singleton) but that does not seem to work because only functions called in the constructor/destructor are actually instantiated (which seems eventually expected because this is just the way templates behave). – OznOg Jul 01 '22 at 14:23
  • Just adding `static const Z z;` or `static const bool instanciate = [] { Z{}; return false; }();` at the end of _T.cpp_ did the trick for me. – paolo Jul 01 '22 at 14:34
  • actually, even the proposed solution does not seem to work: https://godbolt.org/z/14xacYhza – OznOg Jul 01 '22 at 14:59
  • why you want the instantiate? – apple apple Jul 04 '22 at 17:41
  • that is an implementation detail but as this is an helper class, I want to put a maximum of my code in the cpp file. So forcing the template instantiation in the cpp would make sure the link will be successful. – OznOg Jul 04 '22 at 18:14

1 Answers1

0

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...

OznOg
  • 4,440
  • 2
  • 26
  • 35