調用的是模板函數還是重載函數?

來源:互聯網
上載者:User
  1. // MaxTemplate.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include <string>
  6. using namespace std;
  7. inline int const& max (int const& a, int const& b)
  8. {
  9.     return a < b ? b : a;
  10. }
  11. // 傳回兩任意類型的數值中的較大者
  12. template <typename T>
  13. inline T const& max(T const& a, T const& b)
  14. {
  15.     return a > b ? a : b; 
  16. }
  17. // 傳回三個任意類型值中的最大者
  18. template <typename T>
  19. inline T const& max (T const& a, T const& b, T const& c)
  20. {
  21.     return ::max (::max(a,b), c);
  22. }
  23. int main()
  24. {
  25.     ::max(7, 42, 68);       // 調用「接受三個自變數」的函數
  26.     ::max(7.0, 42.0);       // 調用 max<double>(經由自變數推導)
  27.     ::max('a', 'b');        // 調用 max<char>(經由自變數推導)
  28.     ::max(7, 42);           // 調用「接受兩個 int 自變數」的 non-template 函數
  29.     ::max<>(7, 42);         // 調用 max<int>(經由自變數推導)
  30.     ::max<double>(7, 42);   // 調用 max<double>(無需自變數推導)
  31.     ::max('a', 42.7);       // 調用「接受兩個 int 自變數」的 non-template 函數
  32. }

/* 譯註:ICL7.1/g++ 3.2 順利通過本例。VC6 無法把最後一個調用匹配到常規的(non-template)函數max(),造成編譯失敗。VC7.1 可順利編譯,但對倒數第二個調用給出警告:雖然它調用的是 function templatemax(),但它發現常規函數 max()與這個調用更匹配。*/這個例子說明:non-template function 可以和同名的 function template 共存,也可以和其相同類型的具現體共存。當其它要素都相等時,重載解析機制會優先選擇 non-template function,而不選擇由 function template 執行個體化後的函數實體。上述第四個調用便是遵守這條規則:::max(7, 42); // 兩個自變數都是 int,吻合對應的 non-template function但是如果可由 template 產生更佳匹配,則 template 具現體會被編譯器選中。前述的第二和第三 個調用說明了這一點:::max(7.0, 42.0); // 調用 max<double>(經由自變數推導)::max('a', 'b'); // 調用 max<char>(經由自變數推導)調用端也可以使用空的 template argument list,這種形式告訴編譯器「只從 template 具現體中挑選適當的調用對象」,所有template parameters 都自call parameters 推導而得:::max<>(7, 42); // 調用 max<int>(經由自變數推導)另外,「自動類型轉換」只適用於常規函數,在templates 中不予考慮,因此前述最後一個調用調用的是 non-template 函數。在該處,'a' 和 42.7 都被轉型為 int:::max('a', 42.7); // 本例中只有 non-template 函數才可以接受兩個不同類型的自變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.