Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does templates work, are they always inlined?

I can understand how it work if they are inlined. But if they are not, how does it work? does all object files get their own copy of for example the function template anyway?

like image 545
Merni Avatar asked Mar 25 '11 10:03

Merni


2 Answers

Templates will be inlined in the standard meaning of inline, which is more related to the One Definition Rule than to actual code inlining. That is, the linker will not complain if the template functions are defined in more than one translation unit, it will just pick one (beware: random one, current compilers do not complain if you provide different definitions of the template in different translation units!) and leave that in the final binary.

Now, as with all other inline functions, the compiler can decide that it is a good idea to actually avoid the function call and inline the function at the place of call, or it might determine that it is not such a good idea (big function, some compilers don't inline functions with nested loops... whatever the reason) and then it will not perform the actual code inlining.

like image 195
David Rodríguez - dribeas Avatar answered Sep 25 '22 07:09

David Rodríguez - dribeas


Depends on the compiler, but every one I've looked at creates a function that is then callable using the substitued template parameters to generate the code for each varient.

as a (very) simple example:

template <typename T> T Max(T a, T b)
{
    return a > b ? a : b;
}

when invoked as Max<int> and Max<float> and not inlined, the compiler generates (they are decorated in a special way however, to prevent other problems):

int Max(int a, int b)
{
    return a > b ? a : b;
}

float Max(float a, float b)
{
    return a > b ? a : b;
}

This is then stuck at the start of the object and then referenced, then same is done for some inlines too (in MSVC)

like image 40
Necrolis Avatar answered Sep 24 '22 07:09

Necrolis