Kodewick
開始學 →
模板25 / 30

C++ 模板

第 25 課,共 30 課 · 第 6 部分 · 繼承和模板 · 約 20 分鐘

模板讓一份程式碼適用於多種型別,比如 template <typename T> T max_of(T a, T b);呼叫時編譯器根據引數推斷出 T。

第 9 課學過過載:同一個名字,引數型別不同,就寫幾個函式。可要是幾個函式的函式體一模一樣,只有型別不同呢?

main.cpp
1#include <iostream>2#include <string>3 4int max_of(int a, int b) {5    if (a > b) {6        return a;7    }8    return b;9}10 11double max_of(double a, double b) {12    if (a > b) {13        return a;14    }15    return b;16}17 18std::string max_of(std::string a, std::string b) {19    if (a > b) {20        return a;21    }22    return b;23}24 25int main() {26    std::cout << max_of(3, 8) << '\n';27    std::cout << max_of(2.5, 1.5) << '\n';28    std::cout << max_of(std::string("apple"), std::string("pear")) << '\n';29    return 0;30}
輸出
8
2.5
pear

三個函式,除了型別,一個字都不差。要是發現比較寫錯了,得改三處;明天要比 char,還得再抄一遍。模板就是讓你只寫一份,把型別空出來,用到時再填。

函式模板

這一課開頭那三個 max_of 只差型別。把它們換成一個函式模板,只寫一份:

main.cpp
1#include <iostream>2#include <string>3 4template <typename T>5T max_of(T a, T b) {6    if (a > b) {7        return a;8    }9    return b;10}11 12int main() {13    std::cout << max_of(3, 8) << '\n';14    std::cout << max_of(2.5, 1.5) << '\n';15    std::string first = "apple";16    std::string second = "pear";17    std::cout << max_of(first, second) << '\n';18    return 0;19}
輸出
8
2.5
pear

template <typename T> 說:下面這個函數裡的 T 是一個還沒定的型別,叫模板引數。函式體照常寫,凡是要寫型別的地方寫 T。(template <class T> 意思完全一樣,兩種寫法你都會看到。)

template① <typename T②>T③ max_of(T a, T b④) {
  1. ①說明這是一個模板
  2. ②T:還沒定的型別(模板引數)
  3. ③回傳值的型別是 T
  4. ④兩個引數都是 T
函式模板:先說 T 是一個待定的型別,再在要寫型別的地方寫 T

呼叫 max_of(3, 8) 時,編譯器看到兩個引數都是 int,就定下 T 是 int,照著模板寫出一個真正的 int max_of(int a, int b)。max_of(2.5, 1.5) 再寫出一個 double 的,max_of(first, second) 再寫出一個 std::string 的(字串按字母順序比,pear 大)。

點單步:三次都進了 max_of,可第一次 a 和 b 是數,第三次是兩段文字。模板本身不是函式,它是編譯器寫函式用的「模子」;每種型別各有一份。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <string>3 4template <typename T>5T twice(T x) {6    return x + x;7}8 9int main() {10    std::string word = "ha";11    std::cout << twice(21) << " " << twice(word) << '\n';12    return 0;13}
練習 1

什麼型別都能用的 min_of

min_of 只能比 int,下面兩行用不了。只寫一個函式:把它改成函式模板,讓程式顯示下面三行。

要顯示
4
1.5
apple
exercise1.cpp
1#include <iostream>2#include <string>3 4int min_of(int a, int b) {5    if (a < b) {6        return a;7    }8    return b;9}10 11int main() {12    std::string x = "pear";13    std::string y = "apple";14    std::cout << min_of(4, 9) << '\n';15    std::cout << min_of(2.5, 1.5) << '\n';16    std::cout << min_of(x, y) << '\n';17    return 0;18}
輸出
點「執行」或按 Ctrl+Enter

T 是怎麼定下來的

編譯器從引數推出 T,這叫模板引數推導。max_of(T a, T b) 的兩個引數都是 T,所以兩個引數必須推出同一個型別。要是一個整數、一個小數:

main.cpp
1#include <iostream>2 3template <typename T>4T max_of(T a, T b) {5    if (a > b) {6        return a;7    }8    return b;9}10 11int main() {12    std::cout << max_of(3, 2.5) << '\n';13    return 0;14}
輸出
main.cpp: In function 'int main()':
main.cpp:12:24: error: no matching function for call to 'max_of(int, double)'
   12 |     std::cout << max_of(3, 2.5) << '\n';
      |                  ~~~~~~^~~~~~~~

no matching function for call to 'max_of(int, double)':找不到能用的 max_of。原因是從 3 推出 int,從 2.5 推出 double,兩個對不上,T 定不下來。(在自己電腦上,g++ 還會接著顯示幾行 note:,其中一行就是 deduced conflicting types for parameter 'T' ('int' and 'double')。)普通函式會把 3 自動轉成 3.0,推導的時候不會。

辦法是自己寫明 T:在函式名後面加尖括號。寫明瞭就不用推導,引數照普通函式的規矩轉換:

main.cpp
1#include <iostream>2 3template <typename T>4T max_of(T a, T b) {5    if (a > b) {6        return a;7    }8    return b;9}10 11int main() {12    std::cout << max_of<double>(3, 2.5) << '\n';13    std::cout << max_of<int>(3, 2.5) << '\n';14    return 0;15}
輸出
3
3

max_of<double> 把 3 變成 3.0,答案 3;max_of<int> 把 2.5 變成 2,答案也是 3,可它悄悄丟了小數。寫明型別時,想好你要的是哪一種。

讓編譯器推max_of(3, 2.5)編譯錯誤int 和 double 對不上
寫明 Tmax_of<double>(3, 2.5)33 先變成 3.0
兩個引數推出兩個型別,T 就定不下來;寫明 T,就不推導了

注意: 別把字串常量直接交給 max_of:max_of("pear", "apple") 推出的 T 是 const char*,比的是兩個位址,不是文字。要比文字,先放進 std::string。

單選

max_of(T a, T b) 的兩個引數都是 T。哪一個呼叫能編譯?

練習 2

修好它:整數和小數比大小

這段程式碼編譯不過。不要改 max_of,也不要改 12 和 12.5,讓程式顯示 12.5。

要顯示
12.5
exercise2.cpp
1#include <iostream>2 3template <typename T>4T max_of(T a, T b) {5    if (a > b) {6        return a;7    }8    return b;9}10 11int main() {12    std::cout << max_of(12, 12.5) << '\n';13    return 0;14}
輸出
點「執行」或按 Ctrl+Enter

引數是 vector<T>

T 不一定單獨出現。引數可以是 const std::vector<T>&,編譯器從 std::vector<int> 裡推出 T 是 int:

main.cpp
1#include <iostream>2#include <vector>3 4template <typename T>5T sum_of(const std::vector<T>& items) {6    T total = 0;7    for (const T& x : items) {8        total += x;9    }10    return total;11}12 13int main() {14    std::vector<int> steps{4200, 8100, 6500};15    std::vector<double> prices{3.5, 12, 8.25};16    std::cout << "步數:" << sum_of(steps) << '\n';17    std::cout << "金額:" << sum_of(prices) << '\n';18    return 0;19}
輸出
步數:18800
金額:23.75

T total = 0; 在 int 版裡是 0,在 double 版裡是 0.0。回傳值也是 T,所以整數加起來還是整數,小數加起來還是小數。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <vector>3 4template <typename T>5T sum_of(const std::vector<T>& items) {6    T total = 0;7    for (const T& x : items) {8        total += x;9    }10    return total;11}12 13int main() {14    std::vector<int> a{1, 2, 3};15    std::vector<double> b{0.5, 0.25};16    std::cout << sum_of(a) << " " << sum_of(b) << '\n';17    return 0;18}

模板對 T 的要求

模板什麼型別都能填嗎?不是。函式體裡對 T 做了什麼,填進去的型別就得會什麼:max_of 用了 >,sum_of 用了 += 和 = 0。拿一個不會 > 的結構體試試:

main.cpp
1#include <iostream>2#include <string>3 4struct Item {5    std::string name;6    double price;7};8 9template <typename T>10T max_of(T a, T b) {11    if (a > b) {12        return a;13    }14    return b;15}16 17int main() {18    Item tea{"紅茶", 12};19    Item cake{"蛋糕", 18};20    Item best = max_of(tea, cake);21    std::cout << best.name << '\n';22    return 0;23}
輸出
main.cpp: In instantiation of 'T max_of(T, T) [with T = Item]':
main.cpp:11:11: error: no match for 'operator>' (operand types are 'Item' and 'Item')
   11 |     if (a > b) {
      |         ~~^~~

報錯分兩層讀。第一行 In instantiation of 'T max_of(T, T) [with T = Item]':編譯器正在照模板寫 T 是 Item 的那一份,這一份是 main 裡的呼叫要的(在自己電腦上,g++ 還會顯示一行 required from here,指向第 20 行)。接著才是 error:,在第 11 行:no match for 'operator>' (operand types are 'Item' and 'Item'),兩個 Item 不會比大小。

模板的報錯常常這樣:錯在模板裡面,原因在呼叫的地方。修法也有兩種:給 Item 寫一個 operator>(第 17 課),或者別把 Item 交給 max_of。

單選

max_of 的函式體裡寫了 a > b。把哪種型別交給它會編譯不過?

類別範本

類也能空出型別。這一關的 Box 能裝一樣東西,裝什麼型別,建的時候說:

main.cpp
1#include <iostream>2#include <string>3 4template <typename T>5class Box {6public:7    Box(T item) : item_(item) {}8    T get() const {9        return item_;10    }11    void put(T item) {12        item_ = item;13    }14 15private:16    T item_;17};18 19int main() {20    Box<int> coins{25};21    Box<std::string> card{"生日快樂"};22    coins.put(coins.get() + 5);23    std::cout << coins.get() << '\n';24    std::cout << card.get() << '\n';25    return 0;26}
輸出
30
生日快樂

和函式模板不同,類別範本要自己在尖括號裡寫明型別:Box<int>、Box<std::string>。(C++17 起可以寫 Box coins{25}; 讓編譯器推,C++14 不行。)Box<int> 和 Box<std::string> 是兩個不同的類,各有自己的 item_。

點單步:畫面上 coins 的型別是 Box<int>,card 的是 Box<string>,裡面各有一個 item_,一個是數,一個是文字。

Box<int>
  • −item_: int
  • +get()
  • +put()
Box<string>
  • −item_: string
  • +get()
  • +put()
coins: Box<int>
  • item_ = 30
card: Box<string>
  • item_ = "生日快樂"
Box<int> 和 Box<string> 是照著同一個模板寫出來的兩個類,各有各的 item_

小技巧: 成員函式也可以寫在類外面,前面要再寫一遍 template <typename T>,類名寫成 Box<T>:template <typename T> T Box<T>::get() const { return item_; }。

填空點一個填進空格,再點空格可以拿回來

選一樣填進空格,建一個裝 double 的 Box,讓程式顯示 9.5。

1#include <iostream>2 3template <typename T>4class Box {5public:6    Box(T item) : item_(item) {}7    T get() const {8        return item_;9    }10 11private:12    T item_;13};14 15int main() {16    Box price{9.5};17    std::cout << price.get() << '\n';18    return 0;19}
練習 3

在不在範圍裡

Range 只能裝 int,體溫要用 double。把它改成類別範本,讓程式顯示 1、0、1 三行。

要顯示
1
0
1
exercise3.cpp
1#include <iostream>2 3class Range {4public:5    Range(int low, int high) : low_(low), high_(high) {}6    bool contains(int x) const {7        return x >= low_ && x <= high_;8    }9 10private:11    int low_;12    int high_;13};14 15int main() {16    Range<int> age{18, 60};17    Range<double> normal{36.0, 37.3};18    std::cout << age.contains(25) << '\n';19    std::cout << normal.contains(37.8) << '\n';20    std::cout << normal.contains(36.6) << '\n';21    return 0;22}
輸出
點「執行」或按 Ctrl+Enter

Stack<T>

再寫一個有用的:堆疊(stack),像一摞盤子,後放上去的先拿走。裡面用一個 std::vector<T> 存東西,只露出幾個成員函式:

main.cpp
1#include <iostream>2#include <string>3#include <vector>4 5template <typename T>6class Stack {7public:8    void push(const T& x) {9        items_.push_back(x);10    }11    void pop() {12        items_.pop_back();13    }14    const T& top() const {15        return items_.back();16    }17    bool empty() const {18        return items_.empty();19    }20 21private:22    std::vector<T> items_;23};24 25int main() {26    Stack<std::string> history;27    history.push("首頁");28    history.push("搜尋");29    history.push("商品詳情");30    while (!history.empty()) {31        std::cout << "返回:" << history.top() << '\n';32        history.pop();33    }34    return 0;35}
輸出
返回:商品詳情
返回:搜尋
返回:首頁

瀏覽器的「後退」就是這樣:最後開啟的頁面最先退回去。Stack<T> 裡的 std::vector<T> 跟著 T 變:Stack<std::string> 裡是 std::vector<std::string>,換成 Stack<int> 就是 std::vector<int>,一個字不用改。

history

後放上去的先拿走:三次 push 摞上去,pop 每次拿走最上面的

點單步看 history 裡的格子:三次 push 加在後面,每次 pop 從後面拿走。空了以後再 top() 或 pop() 是未定義行為(引擎會停下),所以先問 empty()。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <vector>3 4template <typename T>5class Stack {6public:7    void push(const T& x) {8        items_.push_back(x);9    }10    void pop() {11        items_.pop_back();12    }13    const T& top() const {14        return items_.back();15    }16 17private:18    std::vector<T> items_;19};20 21int main() {22    Stack<int> s;23    s.push(1);24    s.push(2);25    s.push(3);26    s.pop();27    s.push(4);28    std::cout << s.top() << " ";29    s.pop();30    std::cout << s.top() << '\n';31    return 0;32}

你早就在用模板了

回頭看看,這門課從第 11 課起就一直在用模板:

你寫過的是什麼
std::vector<int>類別範本 vector,T 是 int
std::map<std::string, int>類別範本,兩個型別引數
std::unique_ptr<Order>類別範本
std::make_unique<Order>("咖啡")函式模板,寫明瞭 T
std::sort(v.begin(), v.end())函式模板,從引數推導

所以標準庫的容器才什麼都能裝:寫 vector 的人不知道你要放什麼,只寫了一份 vector<T>。std::max(3, 2.5) 也會碰到和 max_of 一樣的推導衝突,修法也一樣:std::max<double>(3, 2.5)。

自己寫模板的時機:發現幾個函式或類只差型別,就把型別換成 T。只給一種型別用的東西,寫普通函式就好,報錯也短得多。

單選

std::max(3, 2.5) 和 max_of(3, 2.5) 一樣編譯不過。怎麼改?

這一課學會了

  • 幾個函式只差型別時,寫一個函式模板:template <typename T>,型別的地方寫 T。
  • 編譯器從引數推出 T,每種型別照模板寫一份函式;單步時看到的是同一個函式名、不同型別的值。
  • 推匯出兩個不同的型別(max_of(3, 2.5))是編譯錯誤;寫明 max_of<double>(3, 2.5) 就不推導了。
  • 引數可以是 const std::vector<T>& 這樣帶 T 的型別。
  • 函式體裡對 T 用了什麼(>、+=),填進去的型別就得會;報錯裡的 In instantiation of … [with T = Item] 說的是哪一份。
  • 類別範本 template <typename T> class Box,用的時候寫明 Box<int>;Stack<T> 可以建在 std::vector<T> 上。
  • vector、map、unique_ptr、sort 都是模板。
第 25 課學完了嗎?第 25 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 26 課 · 25 分鐘異常:try 和 catch出錯時怎麼告訴呼叫的人:throw、try / catch、std::runtime_error 和 what(),接住 v.at() 和 std::stoi 丟擲的異常,丟擲後區域性物件怎麼析構,自己的異常類。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。