2

I want to compile a static library with a template class. I know this cannot be done for every type, but I know that programs that will make use of this library are going to need only a few template "instantiations" (I mean, for a few known types).

Is there a way to manually trigger compilation of the template class for these types within the library itself?

  • look at this [link](https://stackoverflow.com/questions/38644146/choose-template-based-on-run-time-string-in-c) – samini Oct 02 '19 at 11:53
  • Not a fan of the duplicate -- it is way less clear, and the answers don't conver C++11 since it's from 2010. – Quentin Oct 02 '19 at 12:44

1 Answers1

2

Yes: you need an explicit template instantiation.

In your header:

extern template struct YourClass<Foo>;

In your .cpp file:

template struct YourClass<Foo>;

Note that if you're certain that the user won't need any other specialization, you can hide the template definitions as they only need to be visible from the explicit instantiation definition.

Quentin
  • 62,093
  • 7
  • 131
  • 191