C++ Templates - code usage, size of binary

1.9k Views Asked by At

I'm wondering about code size of template code. Please consider following code

template<typename T>
class vector
{
public:

 vector(size_t size) :
 {
     array = new T[size];
 }


 uint32_t push_back(T value)
 {
  ... adding value to array and possible array realloction..  
 }

private:
 T * array;
}

When i have two vector instances,

vector<float> v1;
vector<int> v2;

will it be compiled to binary with two push_back implementations

push_back(float)
push_back(int)

or only one, or something else?

Is it possible to reduce code size with templates instead of creating separated classes for float and int vector?

1

There are 1 best solutions below

3
On BEST ANSWER

Classes and functions instantiated from templates do not have any relation between them at runtime and thus functions will be duplicated.

Some compilers will optimize away shared/duplicate code but this optimization's scope is wider than template instances.

Note that even if the code looks the same it may trigger different function calls when certain operators are used.

This is especially visible for pointer containers like std::vector<int*> and std::vector<char*>, you will get different functions for both although their behavior is practically identical.

To summarize, templates are excellent at reducing code size and but creating many different instances will bloat your binary.