Robin Hsu Robin Hsu - 1 year ago 74
C++ Question

C++ template function, same type, multiple instantiations: shares one same copy of code? EVEN in different cpp/object files

For example, consider the following code:

// f.h
template <typename T>
int f(T x) {
return x+1;

If we instantiate it in both

//foo.cpp instantiation:
int i = f(1);


//bar.cpp instantiation:
int j = f(2);

Will the final program uses only one copy of code? Is that so, when
is hidden but only the object file
is provided?

I think, since each cpp files are compiled independently, both
must contains
. The linker should see same duplicate signature, and use only one copy. Am I right?

Answer Source

Yes, the linker will generally fold duplicate identical template instantiations away. Doing so is pretty much required to avoid an explosion in binary size when templates are involved, and to maintain some standard required invariants such as equivalence of function pointers. This behavior is sometimes called fold by name.

Beyond that, some linkers will even fold away all symbols that happen to be identical in content (i.e., compile the same code), even if they don't originate from the same definition. This is sometimes called fold by value, but unless done carefully may break the letter of the standard (i.e., because function pointers to different functions now compare equal).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download