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 foo
in 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 foo
an inline
function or making it static
. If you want to emit the function template specialization you need to explicitly instantiate it
#else
template< typename T >
void foo( const T &v)
{
std::cout<<v<<std::endl;
}
template void foo(const int&);
#endif
Doing this, my measures give the exact same size for the non-template function and the function template version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With