Deduction pattern interesting case, C ++

Consider this world 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 called a function for 3 types. Although 5 and j may be the same, just int, const int I am definitely different from type.
But in any case, my conclusion:

1
2
3

Thus, this means that the compiler creates the same function for different types. I'm right? Can anyone explain why?

+4
source share
3 answers

From [temp.deduct.call]:

The output of the template argument is done by comparing each parameter of the function template parameter (calling it P) using the type of the corresponding call argument (name it A), as described below.

P const T&, and A- int, intand const intin three challenges.

Then we have:

P , , P, .

P , P' == const T A == int A == const int. T == int , P' == const int ( P == const int&) A == const int. CV, A , OK:

, A A ( , A , ). , :
- P , A ( , ) CV, A.

, f<int>.

+5

f int, 3 f<int>.

+5

That's right, as soon as the output type is entered.

Consider this:

#include <iostream>

template<class T>
void f(const T& t)
{
    static int x = 0;
    std::cout<< "x=" << ++x<<std::endl;
}

template<class T>
void f(T&& t)
{
    static int y = 0;
    std::cout<< "y=" << ++y<<std::endl;
}

template<class T>
void f(T& t)
{
    static int z = 0;
    std::cout<< "z=" << ++z<<std::endl;
}

int main()
{
    int j = 0;
    const int i = 0;
    f(5);
    f(i);
    f(j);
}

Conclusion:

y=1
x=1
z=1
0
source

All Articles