2010-10-02 109 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

編譯器不記得類型。它爲不同類型創建不同的功能。