On Thursday, 23 April 2015 00:39:22 UTC+3, Daniel Davidson wrote:
> Assume you have a class template parameterized by some set of types
> that provides some functionality. In the system there are three
> specific instantiations of that template. In another codebase a
> developer has created exactly the c++ code that those templates
> instantiations (i.e. 3 hand written classes that are verbatim the
> same except for naming). In this situation are there optimizations
> that can make the template version faster than the the handwritten?
One difference is that the templates are header-only.
The ordinary classes (and also full specializations of templates)
are typically split between interface declaration in header file
and translation unit that implements the functionality.
That makes templates to compile slower but gives better
opportunities for the compiler to optimize. Also linkers
sometimes merge code of different instances (that happen to
do exactly same thing) behind same binary code.
> In a nutshell are there advantages to using templates that can make
> it even faster than, say generated code with exactly the same
> content? If there are what are those optimizations?
The efficiency is actually not that interesting advantage. You pay
with slow compilation and linking and achieve that something that
was sufficiently fast is maybe some % faster. The advantage is lack
of maintenance head-ache of the alternative: massive copy-paste.
Lets imagine that there are *only* six copy-pastes of ~500 lines
class and only *one* defect lurking in it.
* The defect is reported by testing about "first" and fixed in that.
* It is reported slightly later in "second" and fixed in that too
but differently, by other guy.
* Some change is requested for "sixth" and yet another maintainer does
modify it but the defect is still there.
* The issue is later found in "third" too but experienced maintainer
senses Déjà vu. So he searches for copy-paste and finds "second",
"third", "fourth" and "fifth". The "first" and "sixth" have been
changed enough so search engine did not find those. He fixes the
4 copies he found in third way.
* Same change is requested for others five that was done in "sixth".
The two different fixes that are applied now to "second" did break
something else in it and "sixth" is still broken. Other five need
to be changed. Bear in mind that it was oversimplified toy example.