Dinushan
Dinushan

Reputation: 2077

Compilation process of programs using C++ templates

Say the following codes are written for the same purpose.The rest of the code of the programs are the same.
code1

#include <vector>
using namespace std;
vector<int> vector1;
vector<int> vector2;
vector<int> vector3;
vector<int> vector4;

code2

 #include <vector>
using namespace std;
vector<int> vector1;
vector<short> vector2;
vector<char> vector3;
vector<bool> vector4;

now which one is better (let in terms of executable size) ? (hint : consider the executables)

I compared the assembly result given by g++ -S .
Surprisingly the number of lines of the second program is 1778 , the first one is 630. Which means the first one is better.
To reason this behavior, I looked for a good resource for "how the template based programs are compiled" but I couldn't find one.

How the programs that use templates are compiled in to assemblies by the compiler ? Do you have a good resource ? (this is not a homework,but a self study problem given in my workplace.Should you feel not to give an answer at least direct me to a good resource)

Upvotes: 0

Views: 202

Answers (1)

Gorpik
Gorpik

Reputation: 11038

The behaviour you find is not surprising at all. The compiler generates as many classes as it needs using the template. In your first example it only needs to generate one (vector<int>), while in your second it needs to generate four. Of course, this generates more code.

As for the question of which one is better: the one that better serves its purpose, of course. But only you are in a position to know that.

Upvotes: 7

Related Questions