views:

90

answers:

2

Given the code:

#include <iostream>
using namespace std;
template <typename T>
T my_max (const T &t1, const T &t2)
{
    static int counter = 0;
    counter++;
    cout << counter << " ";
    return ((t1 > t2) ? t1 : t2);
}
int main()
{
    my_max (2,3);
    my_max (3.5, 4.3);
    my_max (3,2);
    my_max ('a','c');
}

The output is:

1 1 2 1

I understand that the static member is initialized only once. My question is how the compiler remembers what types called that generic function? What actually happens behind the scenes?

+8  A: 

What happens is that the compiler instantiate the function for every type(used one of course). So, you would have the following "functions" internally:

int my_max (const int &t1, const int &t2)
{
    static int counter = 0;
    counter++;
    cout << counter << " ";
    return ((t1 > t2) ? t1 : t2);
}
...
double my_max (const double &t1, const double &t2)
{
    static int counter = 0;
    counter++;
    cout << counter << " ";
    return ((t1 > t2) ? t1 : t2);
}
...
char my_max (const char &t1, const char &t2)
{
    static int counter = 0;
    counter++;
    cout << counter << " ";
    return ((t1 > t2) ? t1 : t2);
}

I think it is clear, that each function is an independent one. They share nothing, except that they are generated by the same template code.

AraK
+2  A: 

The compiler doesn't remember the types. It creates different functions for different types.

Max