4

I have a template struct with a non-type parameter, each instantiation of it takes a long time to compile. I know realistically I will only need to instantiate it for a few dozen or so different size_t parameters. A minimal example would be something along the lines of:

///foo.h///
template <size_t A>
struct Foo{
   void bar();
};

extern template struct Foo<1>;
extern template struct Foo<2>;
extern template struct Foo<3>;
// and so on...
extern template struct Foo<25>;

///foo.cpp///
#include "A.h"
template <size_t A>
void Foo<A>::bar(){
   // Do something that depends on A at compile time and 
   // has lots of expression templates so it takes a while
   // to compile
}

template struct Foo<1>;
template struct Foo<2>;
template struct Foo<3>;
// and so on...
template struct Foo<25>;

///main.cpp///
#include "A.h"
int main(){
   //Use any Foo<n> for n in 1...25 here without needing
   //template instantiation in this translation unit
   return 0;
}

Is there any way using template metaprogramming to avoid having to write out all 25 explicit instantiations in foo.h and foo.cpp? Or will I have to use a macro for this?

cigien
  • 57,834
  • 11
  • 73
  • 112
  • Seems like this is probably going to need [`std::integer_sequence`](https://en.cppreference.com/w/cpp/utility/integer_sequence) – Fantastic Mr Fox Aug 10 '21 at 02:56
  • @FantasticMrFox getting a parameter pack of `` from 1 to 25 seems like it'd be part of the solution, but then what? My problem is seems these explicit instantiations have to be declared at the top level, not inside templated structs or functions to which I can pass that parameter pack. – John Robinson Aug 10 '21 at 03:22
  • @DavisHerring I am not sure that is an exact duplicate – Fantastic Mr Fox Aug 10 '21 at 04:30
  • Not sure it is possible to have **explicit** instantiations that way :/ (implicit ones should be possible though). – Jarod42 Aug 10 '21 at 09:17
  • An idea would be to make a temporary struct `T` that depends on `Foo<1>` ... `Foo<25>`, then explicitly instantiate `T`. – user202729 Aug 15 '21 at 09:03
  • Try to use struct instead of function. I have done some tests before and it show that structs has much faster compilation than functions. – Vladimir Talybin Aug 25 '21 at 09:03

0 Answers0