Static elements and patterns in C ++

Based on 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');
}

Conclusion:

1 1 2 1

I understand that a static member is initialized only once. My question is, how does the compiler remember what types called this generic function? What is really going on behind the scenes?

+3
source share
2 answers

What happens is that the compiler creates an instance of the function for each type (used, of course,). This way you will have internal functions:

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 independent. They have nothing, except that they are generated by the same template code.

+8
source

The compiler does not remember types. It creates various functions for different types.

+2
source

Source: https://habr.com/ru/post/1767699/


All Articles