Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do templates shorten the size of source or binary or both

Tags:

c++

I read that templates are complied into different entities so does that mean the binary size will be same as we have complied it using different functions?

like image 812
new Avatar asked Jul 27 '10 08:07

new


People also ask

How are C++ templates implemented?

Class templates are generally used to implement containers. A class template is instantiated by passing a given set of types to it as template arguments. The C++ Standard Library contains many class templates, in particular the containers adapted from the Standard Template Library, such as vector .

Can templates be defined in CPP?

A template is a C++ entity that defines one of the following: a family of classes (class template), which may be nested classes. a family of functions (function template), which may be member functions.


2 Answers

They should shorten the source size (if they are reused) but not the binary size (the template is compiled for each different instantiation).

This differs from Java generics, where there is a full type erasure (generics only serve as a compile time verification of types) or C#, where generics are compiled into specific binaries that can be directly reused without having to recompile and generate more code.

like image 137
David Rodríguez - dribeas Avatar answered Sep 22 '22 05:09

David Rodríguez - dribeas


My understanding is that for each type you instantiate with a template the complier produces the relevant class to match that type - so if you use List<int>, List<foo> and List<float> there will effectively be three different List classes in your complied binary.

Edit:
What I didn't explicitly state was that I'm inferring that merging several classes in to a single template will (probably) not reduce the size of your binary, but should reduce the size of your source.

like image 27
DMA57361 Avatar answered Sep 21 '22 05:09

DMA57361