Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template code increase size of a binary

Tags:

c++

templates

g++

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.

like image 641
BЈовић Avatar asked Nov 23 '11 20:11

BЈовић


1 Answers

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.

like image 135
Johannes Schaub - litb Avatar answered Nov 13 '22 12:11

Johannes Schaub - litb