Since template code is generated at compile time, it implies that there should be a separate set of code for each template objects created. Does that mean templates increase the executable size?
Not necessarily. Whether templates increase the program’s size depends on how you’re actually using them in your code and the compiler’s cleverness. It is true that injudicious usage of templates can cause a problem known as “code bloat”. For example, one of the following instances of the vector template is redundant; on a 32-bit platform, both of them result in two copies of identical code:
vector < int > vi; vector < long > vl;
Worse yet, because pointer types are distinct, excessive instantiation of pointer-based templates also creates redundant copies of identical code:
// Shape is base of Rectangle and Squarevector < Shape* > vs; vector < Rectangle* > vr;vector < Square* > vsq;
In this case, three distinct copies of vector are instantiated, one for each pointer type. You can easily avoid this redundancy by using polymorphism and a vector of a pointer to the base class, i.e., vector < Shape* >:
Rectangle rec;vs.pushback (&rec); // pointer to derived// calls Rectangle::Draw if vs is of type Rectangle*vs->Draw();
In fact, sophisticated use of templates can actually reduce the program’s size rather than increase it. This is because the compiler must generate code on a selective basis: it generates code only for member functions that are actually used in the program, whereas member functions that aren’t referenced in the program aren’t generated. Thus, if vector has 25 member functions (including constructors, assignment operator, and destructor). However, if a program only uses the push_back(), operator , default constructor and destructor of vector < Shape* >. In this case, the compiler doesn’t generate code for the rest of the member functions. Consequently, program’s size is reduced. By contrast, if you’d chosen to implement vector as an ordinary class (i.e., not a class template), the compiler would have generated code for all the member functions of that class.