2012-02-09 283 views
1

這個例子是C++模板書約祖蒂斯:C++函數模板重載

#include <iostream> 
#include <cstring> 
#include <string> 

// maximum of two values of any type (call-by-reference) 
template <typename T> 
inline T const& max (T const& a, T const& b) 
{ 
    return a < b ? b : a; 
} 

// maximum of two C-strings (call-by-value) 
inline char const* max (char const* a, char const* b) 
{ 
    return std::strcmp(a,b) < 0 ? b : a; 
} 

// maximum of three values of any type (call-by-reference) 
template <typename T> 
inline T const& max (T const& a, T const& b, T const& c) 
{ 
    return max (max(a,b), c); // error, if max(a,b) uses call-by-value 
} 

int main() 
{ 
    ::max(7, 42, 68);  // OK 

    const char* s1 = "frederic"; 
    const char* s2 = "anica"; 
    const char* s3 = "lucas"; 
    ::max(s1, s2, s3); // ERROR 

} 

他說,在::max(s1, s2, s3)錯誤的原因是,C-字符串max(max(a,b),c)調用max(a,b),創建一個新的臨時局部值可能會被函數返回的引用。

我沒有得到如何創建一個新的本地值?

+0

您確定您正確地複製了本書中的代碼嗎?我認爲'inline char const * max'應該是'inline char const * const&max' – 2012-02-09 06:40:41

+1

'inline T const&max(T const&a,T const&b,T const&c)'的最後一個返回將仍然返回一個對本地值(指針),一旦max完全返回就會停止存在。 – devil 2012-02-09 07:24:39

+0

傑西,這個例子來自Josuttis的網站......(http://www.josuttis.com/tmplbook/)...它的'basics/max3a.cpp' – amneet 2012-02-09 16:11:26

回答

0

對於C-字符串,這個代碼創建一個局部值,即,存儲的地址(類型char const的*的指針)的局部變量:

的std ::的strcmp(A,B)< 0? b:a;

因此,返回對此的引用(使用模板函數)會導致錯誤。在這種情況下,在C字符串max已經返回副本之後,char const * const &類型的引用返回給本地模板函數max。模板函數必須通過值而不是引用返回指針。

模板函數需要爲指針類型重載。