Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template deduction interesting case, c++

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?

like image 227
Eduard Rostomyan Avatar asked Dec 24 '22 17:12

Eduard Rostomyan


1 Answers

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

like image 133
Barry Avatar answered Jan 10 '23 03:01

Barry