It seems like when invoking a function explicitly, it should be compiled at compile-time with a specific variable type, but I am not sure how implicit function invokation works. I don`t think compiler will create a different function for evey datatype available (since there can be many different data-types in one program). So can someone explain how the templates work, and how they effect performance of the peogram¿ I understand that different compilers can implement them differently, so a link to a compiler-specific technical writting will suffice me.

Some of the more popular implementations do generate a copy of the instantiation code in each object file which triggers an instantiation, and count on the linker to throw out all but one. Other compilers use some sort of repository, where instantiations are stored; if the instantiation is already present, the compiler doesn't bother regenerating it. This solution is significantly faster and uses less disk than the first solution, but it's also a lot harder to get right. (The compiler has to generate a new instantiation not only if one isn't present, but if any of the files the instantiation depends on have changed.)

Edited 5 Years Ago by sundip: n/a

Template instantiation is done at compile-time; no there is no run-time overhead for instantiating a template.

> but I am not sure how implicit function invokation works.
> I don`t think compiler will create a different function for evey datatype available
> (since there can be many different data-types in one program).

Yes. AFAIK, every implementation creates a different instantiation each time. This can lead to code bloat for template functions containing a significant amount of code; you may want to write your code in such a way that this issue is addressed.
See: http://drdobbs.com/184403053

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.9
Some what dated; in current C++, you would use std::enable_if<> and friends.

C++ requires that each template instatiation occurs exactly once in the program if it is needed, and not at all otherwise. There is also a code bloat problem if the implementation violates this rule. I haven't checked the situation with the more recent versions, but g++ used to be (and probably still is) a notorious violator.
See: http://docs.freebsd.org/info/gcc/gcc.info.Template_Instantiation.html

Edited 5 Years Ago by vijayan121: n/a

you may want to write your code in such a way that this issue is addressed.

I would rather use type_traits to avoid the problem of code bloat.
type_traits is ease to use, although the syntax is a little bit verbose

Edited 5 Years Ago by stereomatching: n/a

This question has already been answered. Start a new discussion instead.