簡體   English   中英

C ++函數模板重載

[英]C++ function template overloading

這個例子來自Josuttis的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)會創建一個新的臨時局部值,該函數可以通過引用返回。

我不知道如何創建新的本地價值?

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

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

因此,返回對此的引用(使用模板函數)會導致錯誤。 在這種情況下,在C字符串max返回一個副本之后,模板函數max返回對char const * const &類型的局部引用。 模板函數必須按值而不是引用返回指針。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM