Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce compile time with C++ templates

I'm in the process of changing part of my C++ app from using an older C type array to a templated C++ container class. See this question for details. While the solution is working very well, each minor change I make to the templated code causes a very large amount of recompilation to take place, and hence drastically slows build time. Is there any way of getting template code out of the header and back into a cpp file, so that minor implementation changes don't cause major rebuilds?

like image 604
SmacL Avatar asked May 13 '10 14:05

SmacL


People also ask

Do templates increase compile time?

Templates are not free to instantiate. Instantiating many templates, or templates with more code than necessary increases compiled code size and build time.

Why do templates take so long to compile?

Because we're adding more templated member functions! Each empty template member function costs about 0.000030 seconds to compile, and that's before it has any code code in it. By moving code out of one function and into another, we actually end up adding time.

Are templates resolved at compile time?

All the template parameters are fixed+known at compile-time. If there are compiler errors due to template instantiation, they must be caught at compile-time!


1 Answers

Several approaches:

  • The export keyword could theoretically help, but it was poorly supported and was officially removed in C++11.
  • Explicit template instantiation (see here or here) is the most straightforward approach, if you can predict ahead of time which instantiations you'll need (and if you don't mind maintaining this list).
  • Extern templates, which are already supported by several compilers as extensions. It's my understanding that extern templates don't necessarily let you move the template definitions out of the header file, but they do make compiling and linking faster (by reducing the number of times that template code must be instantiated and linked).
  • Depending on your template design, you may be able to move most of its complexity into a .cpp file. The standard example is a type-safe vector template class that merely wraps a type-unsafe vector of void*; all of the complexity goes in the void* vector that resides in a .cpp file. Scott Meyers gives a more detailed example in Effective C++ (item 42, "Use private inheritance judiciously", in the 2nd edition).
like image 87
Josh Kelley Avatar answered Oct 03 '22 23:10

Josh Kelley