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.

Recommended Answers

All 3 Replies

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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.