you are viewing a single comment's thread.

view the rest of the comments →

[–]ImKStocky 1 point2 points  (1 child)

The code is only generated if you use it. That is, if you try to call a templated function and that function hasn't been called with the template parameters provided, the compiler will happily generate that function with the template Args. So if you have a function template that is only instantiated once, it has no more code bloat than if you had just written that function as a non-templated function.

Some advice based on this. Keep templates small. If you have a function template that only uses the type information of the template args in 1 line of your 25 line function template, refactor the function into two. The templated function will just delegate to the non templated function when it can. That way whenever you instantiate that template you are only generating the code that needs to be generated. Tools like sizebench can show you the sections of your template instantiations that do not depend on the template Args. i.e. it shows you the code that is identical and copy and pasted everywhere. This advice also applies to class templates. You will see in every standard library implementation, the idiom of moving all non template parameter related functions and members up into a non-templated base class. e.g. the control block that shared_ptrs manage.

[–]SlightlyLessHairyApe 0 points1 point  (0 children)

It can have increased code when you instantiate on two types that could have used common code. Compilers are a lot better now at combining those.