2013-03-28 74 views
3

我正在研究函數的模板。爲了簡化,說它看起來像這樣:C++模板C字符串參數

template < typename T > 
void f(const T & x) 
{ 
    cout << "generic case" << endl; 
    cout << x << endl; 
} 

我一直認爲C字符串不能用作模板參數參數。但實際以下工作(使用G ++ 4.5.1):

f("hello world"); 

所以我的問題是:什麼是T當我叫f("hello world")

我想專門看看究竟發生了什麼。例如,因爲char[]const char*我看着這個(這顯然是行不通的):

template < typename T > 
void f(const T & x) 
{ 
    cout << "generic case" << endl; 
    cout << x << endl; 
} 
template <> 
void f(const const char * T & x) 
{ 
    cout << "char[] case" << endl; 
    cout << x << endl; 
} 

,並嘗試了幾種變化。他們都沒有工作。

題外話:我並不真的需要這對我在做什麼。我需要爲T =「C字符串」的情況下,所以我只寫了另一個模板功能的專業化:

template < typename T > 
void f(const T & x) 
{ 
    cout << "generic case" << endl; 
    cout << x << endl; 
} 
template < typename T > 
void f(T x[]) 
{ 
    cout << "T[] case" << endl; 
    cout << x << endl; 
} 

我只是問,因爲我很好奇,究竟是什麼發生的事情,爲什麼是C字符串允許成爲模板參數,當我讀過的時候說它不能是。我一定誤解/誤解了有關模板的內容。

+0

可能重複:http://stackoverflow.com/questions/6973040/specialize-a-void-function-template-to-a-const-charn – 2013-03-28 04:51:09

回答

3

沒有C-string類型。術語C字符串定義了內容,而不是類型。它指的是字符數組的一部分,它的某個地方有一個空字符,它被某些函數解釋爲意味着字符串的結尾。

你是什麼人在思想上真正感興趣的,是一個字符串文字。字符串文字的類型爲const char[N],其中N是字符串中的字符數,包括隱式空終止符。所以"hello world"的類型是const char[12]。您可以專門爲它是這樣的:

template<> 
void f(const char(&x)[12]) 
{ 
    cout << "const char[12] case" << endl; 
    cout << x << endl; 
} 

注意,這僅覆蓋大小12的陣列。然而,你可以重載,(不是專業)f()所有尺寸是這樣的:

template<size_t N> 
void f(const char(&x)[N]) 
{ 
    cout << "const char[" << N << "] case" << endl; 
    cout << x << endl; 
} 

還要注意,這些方法也會覆蓋正常的命名數組。沒有辦法區分它們和字符串文字。

0

。注意,這也將作爲爲const char [N]和常量字符*既會推斷出,

template < typename T > 
void f(const T* x) 
{ 
    cout << "const char* case" << endl; 
    cout << x << endl; 
} 

專業化這裏是恆定指針類型。

如果您需要基於char數組類型或指針類型的特化,則還可以使用簡單函數重載。