2010-10-02 106 views
3

鉴于代码:静态成员和模板在C++

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

的输出是:

1 1 2 1 

据我所知,静态部件是只有一次初始化。 我的问题是编译器如何记住什么类型称为通用函数?幕后发生了什么?

回答

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); 
} 

我认为很清楚,每个功能是独立的。除了它们由相同的模板代码生成外,它们什么也不分享。

2

编译器不记得类型。它为不同类型创建不同的功能。