venkysmarty
venkysmarty

Reputation: 11431

compilation control and code bloat in templates

I am reading about templates in apllied C++ book and it is mentioned as below

Templates create code bloat. The compiler will instantiate a template object for each pixel type. Even if your users only need limited types, the image processing routines may need additional types for temporary images and the like.

Not having to be templated object has the advantage of giving us control of how the object will be compiled, and lets us control code bloat.

My questions on above text

  1. What does author mean by "Even if your users only need limited types, the image processing routines may need additional types for temporary images and the like." ?

  2. What does author mean by "Not having to be templated object has the advantage of giving us control of how the object will be compiled" ?

Request your help in understanding above statements. It would be good if explained with simple examples.

Thanks for your time and help.

Upvotes: 2

Views: 272

Answers (1)

Matthieu M.
Matthieu M.

Reputation: 299810

The author is right that templates may create so-called code-bloat, but his explanations are fuzzy...

Let us a start with a primer on code-bloat.

There is an annoying interaction in the C++ Standard between templates and function pointers:

  • Each instantiation of a template with a given set of parameters is its own types
  • Two different functions should have different addresses

Since two different instantiations (one with int and one with long for example) are different types, the functions associated with them are different functions, and thus they need different addresses.

An optimizing compiler is allowed to actually merge functions under the as-if rule: if the programmer cannot realize they were merged. The naive attempt is to try and prove that the address of one of them is never taken, this is futile. A more clever strategy is to merge the function bodies, but still provide a different address:

; assembly-like code
function_instantiation_1:
    nop                   ; offset to have different addresses
function_instantiation_2:
                          ; body of both functions

However a practical problem is to identify such functions that could be merged, given the sheer number of functions there are.


So ? If one wishes to limit the amount of code produced, one just has to limit the number of instantiations. I find the author claim that the image processing routines may need additional types for temporary images and the like dubious. The set of types within a program is generally fairly restricted, and there are not gazillions of image types.

Upvotes: 2

Related Questions