Template instantiation

Hi,

Let's say I defined a template function or a template class which is designed to take int or double. I use it for the first time with int arguments so the template is instantiated using int. During instantiation a code is actually generated. Then I use this template second time with int argument, so is it considered that it is instantiated again? Is new code generated again or compiler is using code from the the first time I used my template with int?

TY

I believe the compiler re-generates the code each time the function is used.

This actually happens before the full compilation happens so you can think of it as a direct text-replacement. That's why you need to have the source of your templated functions in the headers. There is no linking at this point.

It's the same thing with inline functions. It's not a real function, the code actually gets replaced in-line before it's compiled. It's like a more sophisticated #define macro which obeys the rules of scope, local variables, type-casting, etc.
Each instantiation (explicit or implicit) generates code only once per whole program, except for some (broken under every C++ standard's [lex.phases]/8) compilers that build them once per object file (but even then, the linker throws out the extra copies of the code when building the whole program. GCC docs call that "Borland model")

PS: a template function, of course, gets inlined where possible, so it can be compiled into code several times if that's beneficial, but in general, templates are nothing like macros.
Last edited on
> Each instantiation (explicit or implicit) generates code only once per whole program.

So, if I have a function template compare(...) not inlined
1
2
compare(10,11);  // First time usage, instantiation -> code generated.
compare(20,21);  // Second time usage, no instantiation -> code is not generated ? 


Is this correct?
yes, more or less for the borland-model compilers if the function wasn't inlined (cfront-model compilers just register those instantiations and generate their code a later stage)
I see, thank you.
Topic archived. No new replies allowed.