yotamoo
yotamoo

Reputation: 5452

differences in compiling normal/template functions, c++

I read this in a tutorial:

It turns out that C++ does not compile the template function directly. Instead, at compile time, when the compiler encounters a call to a template function, it replicates the template function and replaces the template type parameters with actual types

I though it was the same with regular (non-templated) functions. I am trying to understand how the compiler treats both kinds of function, and where is the main difference. Thanks!

Upvotes: 3

Views: 63

Answers (1)

Fred Foo
Fred Foo

Reputation: 363787

I though it was the same with regular (non-templated) functions.

No. Most compilers, when compiling a (non-static) function, will just emit object code for that function (which they might later change when doing whole-program optimization, but not all compilers do that). This is not done for template functions, since (a) those may not contain enough information to emit all of the object code and (b) they may accept an infinite number of possible values for their template arguments, so the compiler would have to compile an infinite number of functions.

Consider

template <typename T>
T add1(T x)
{
    return x + 1;
}

This template function can be applied to any type T for which operator+ is defined and can take an int argument, and since you can make such types yourself with operator overloading, there's a potentially infinite number of them.

Instead, at compile time, when the compiler encounters a call to a template function, it replicates the template function and replaces the template type parameters with actual types

... but the linker will notice that, if you use add1 on the same type T (say, float) in multiple modules, the compiled object code is the same in every case, and it will remove the duplicates.

Upvotes: 2

Related Questions