It is often said that the code with lots of templates is going to cause the output to increase in size, but is it really true?
#include <iostream>
#if 0
void foo( const int &v)
{
std::cout<<v<<std::endl;
}
#else
template< typename T >
void foo( const T &v)
{
std::cout<<v<<std::endl;
}
#endif
int main ()
{
foo(50);
}
The example above produces outputs of different sizes (6.19k with the function, and 6.16k with a template function). Why is the version with a template smaller?
If it matters, I am using g++ 4.6.1, with next options -O3 -Wextra -Wall -pedantic. I am not sure what is the output of other compilers.
Perhaps because
fooin your example has external linkage so that it is emitted into your executable even if the call is inlined.For the template, if the call is inlined there is no reason to emit an implicitly instantiated function template specialization.
Try making
fooaninlinefunction or making itstatic. If you want to emit the function template specialization you need to explicitly instantiate itDoing this, my measures give the exact same size for the non-template function and the function template version.