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?
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.
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)
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