Search code examples
c++templatesshared-libraries

compile C++ header-only templates to a shared library


I'm working on a code base of template classes. It's header-only (no .cpp files). I would like to hide implementation and provide a shared library plus a couple of headers containing only declaration. Unfortunately sounds like doesn't make a sense. Since there is no compiled code, so what will be in such a shared lib? Trying to remove definitions from headers after compiling, causes undefined references. Is there a way to force compiler to ship objects in dll or shared library without having to explicitly instantiate template classes?


Solution

  • No, there isn't and wont be a way to do that for the foreseeable future. The only way to provide template C++ code is as header files only. Modules might change that, but that is unlikely to happen before your library is finished.

    Something you can try is to split into implementation and explicitly instantiate all possible use cases. Then the library you ship wont work with any other types then the instantiated ones and would significantly reduce the benefit templates bring.