Chris
Chris

Reputation: 239

How does template cause the code bloat in C++?

I never understood this issue with templates. For me instantiating a method multiple types for different type of parameter is same as implementing the same in terms of function overloading. If this is the case how template causes the code bloat or exceeds the binary size to a certain limit. Please bring clarity into this.

Sometimes I am unsure whether to use templates or function overloading. Template code bloat is the problem I have heard of, but never understood.

Upvotes: 12

Views: 12859

Answers (2)

Captain Obvlious
Captain Obvlious

Reputation: 20063

How does template cause the code bloat in C++?

Code bloat occurs because compilers generate code for all templated functions in each translation unit that uses them. Back in the day, the duplicate code was not consolidated, which resulted in "code bloat". These days, the duplicate code can be removed at link time.

Upvotes: 10

Evan Dark
Evan Dark

Reputation: 1341

Templates are they are not final code cannot be compiled and linked so templates are lost when compiling is done, and the final object file does not contain any template definitions, only the instantiated methods.

This comes with a consequence we are all used to: templates libraries are header only. They are just like static functions in this regard, each translation unit uses their own copy of the same template function. In C++11 you can prevent this with using extern templates, but that's far from automatic, and usually it doesn't even worth the time.

The second issue is that unlike using unions, void * pointers or object inheritance, which are tools that reuse existing code, templates are stupid, and they will generate new code, even if it's the same for any type.

for example:

void * malloc(size_t int);

template<class T> T * talloc(size_t int);

the second function will generate different code for all T types, even though the generated code will be the same.

Of course the compiler will also try and save on the genarated functions. For each class only the functions that are actually used in that translation unit will be generated for any template parameters.

But since the virtual table needs the addresses of all virtual functions if you have a virtual template class, all virtual functions will be generated for any parameter combinations.

Upvotes: 3

Related Questions