iT邦幫忙

2025 iThome 鐵人賽

DAY 18
1
Software Development

30 天 Effective C++ 大挑戰!!系列 第 18

[Day 18] Templates and Generic Programming I

  • 分享至 

  • xImage
  •  

隨著章節內容的深入,難度逐漸上升。為了保障學習品質,從這個篇章開始將放慢閱讀速度,希望能仔細消化每一個重要觀念!

41. Understand implicit interfaces and compile-time polymorphism

Class 與 template 的「介面」與「多型」皆存在,但表現形式不同。對 class 來說介面是顯式的,基於函式簽名,支援執行時多型;對 template 來說介面是隱式的,基於有效表達式,支援編譯時多型。

隱式介面不會有明確的標註或定義。開發者在使用這樣的介面時,需要根據具體情況來推斷其實現或功能。

用以下模板函數舉例。模板參數中的 Student 並不是一個具體的類型,而是一個通用的占位符

template<typename Student>  
void doExam(Student& s) {  
    // implement here...
}

而在 doExam 被實際調用時,會被具體化doExam(Yoyo&),並接受一個 Yoyo& 類型的參數:

Yoyo y;
doExam(y);

42. Understand the two meanings of typename

「巢狀依賴型別」是指那些依賴於模板參數的型別名稱,例如 C::const_iterator 等。其需要使用 typename 避免歧義,讓編譯器確定該語法是型別而非其他元素。

而以下幾種情況並不需要 typename

  • 在繼承列表中繼承基底型別時。
  • 在成員初始化列表中作為基底型別識別符時。
  • 使用 typedef 簡化巢狀型別名稱,常見於泛型程式設計。
  • 在模板參數的宣告中,classtypename 可互換。

上一篇
[Day 17] 中場休息 Q&A小測驗!!
下一篇
[Day 19] Templates and Generic Programming II
系列文
30 天 Effective C++ 大挑戰!!30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言