0

To explicitly instantiate a class template I can do the following:

//.h
template<typename T>
class Foo{};


//.cpp
template class Foo<float>;

This is nice because the Foo<float> class will only have to be instantiated once now when being used from many places. Would it be possible to explicitly instantiate Foo<T> with a tuple of predetermined types? Lets say the tuple is std::tuple<float, int, bool>, which I want to use to instantiate Foo<float>, Foo<int> and Foo<bool>

Andreas Loanjoe
  • 2,205
  • 10
  • 26

1 Answers1

1

If you want to conveniently instantiate several Foo template classes, you could simply provide a wrapper for that:

template<typename ...Ts>
class MultiFoo : public Foo<Ts>... {};

and then to instantiate several template classes at once:

template class MultiFoo<int, double, bool>;

which will instantiate Foo<int>, Foo<double>, and Foo<bool> for you.

Here's a demo

If you actually have a tuple, then you can provide an explicit specialization for that:

template<typename ...>
class MultiFoo;

template<typename ...Ts>
class MultiFoo<tuple<Ts...>> : public Foo<Ts>... {};

and instantiate several Foos with:

template class MultiFoo<tuple<int,double, bool>>;

Here's a demo, where I added my own tuple so that the output is actually visible. This should work exactly the same way for std::tuple.

Note that if you want to explicitly instantiate templates so that they are visible in other translation units, you need to use the extern keyword for that. e.g.

extern template class Foo<int>;

and

extern template class MultiFoo<int, double, bool>;
cigien
  • 57,834
  • 11
  • 73
  • 112
  • The problem is that I have the types stored in a tuple that will be changed later. – Andreas Loanjoe Apr 16 '20 at 14:59
  • Oh, I see. Let me try that out. – cigien Apr 16 '20 at 15:01
  • @AndreasLoanjoe added the tuple version. – cigien Apr 16 '20 at 15:08
  • This results in unresolved external symbols when using Foo in another translation unit. It doesn't seem to be explicitly instantiating Foo, nice idea though didn't try that one yet. – Andreas Loanjoe Apr 16 '20 at 15:19
  • @AndreasLoanjoe I've added the solution to this to the answer. – cigien Apr 17 '20 at 16:48
  • That doesn't really solve the problem though because now I still need to write out the list of instances I want in the header manually, without being able to update them when updating the tuple. – Andreas Loanjoe Jun 10 '21 at 20:19
  • @AndreasLoanjoe What exactly do you mean by "update the tuple?" If you're doing the update at run time, this is not possible. – cigien Jun 10 '21 at 22:56
  • No I mean when a type gets added to the system (by editing the tuple), I want it to be part of the explicit instantiations that can be seen from another translation unit. If I have to indicate every version as extern I cannot do that without macros. – Andreas Loanjoe Jun 11 '21 at 09:15