Consider this peace of code:
template<class T>
void f(const T& t)
{
static int x = 0;
cout<<++x<<endl;
}
int main()
{
int j = 0;
const int i = 0;
f(5);
f(i);
f(j);
}
I have called the function for 3 types. Although 5 and j can be the same thing, just int, const int i is definitely different type.
But anyway my output is:
1
2
3
So that means that compiler instantiates the same function for different types.
Am I correct? Can anybody explain why?
From [temp.deduct.call]:
Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below.
P
is const T&
and A
is int
, int
, and const int
in the three calls.
We then have:
If P is a reference type, the type referred to by P is used for type deduction.
P
is a reference type, so we use P' == const T
for deduction against A == int
or A == const int
. In both cases, we deduce T == int
so that P' == const int
(and P == const int&
) and the deduced A == const int
. This is more cv-qualified than the original A
for the first two calls, but that's explicitly made OK:
In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above). However, there are three cases that allow a difference:
— If the original P is a reference type, the deduced A (i.e., the type referred to by the reference) can be more cv-qualified than the transformed A.
Thus, all three cases just call f<int>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With