简体   繁体   中英

Static members and templates in c++

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM