c ++中的静态成员和模板

San*_*ich 3 c++ generics static

鉴于代码:

#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');
}
Run Code Online (Sandbox Code Playgroud)

输出是:

1 1 2 1
Run Code Online (Sandbox Code Playgroud)

我知道静态成员只初始化一次.我的问题是编译器如何记住调用该泛型函数的类型?幕后实际发生了什么?

Ara*_*raK 8

会发生什么是编译器为每种类型实例化函数(当然使用其中一种).那么,你将在内部拥有以下"功能":

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);
}
Run Code Online (Sandbox Code Playgroud)

我认为很明显,每个功能都是独立的.除了它们是由相同的模板代码生成之外,它们不共享任何内容.