c++templatesexplicit-instantiation

Explicitly instantiate templates using a tuple


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>


Solution

  • 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>;