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?
What happens is that the compiler instantiate the function for every type(used one of course). So, you would have the following “functions” internally:
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.