C++ 標準委員會持續擴充標準庫,Tuple (元組) 是近期加入的強大資料類型。它是大小固定、異構型別的物件集合,能優雅解決多返回值、多值比較/賦值、異構資料打包等常見痛點。現代編譯器 (GCC 7+, Clang 5+, MSVC 19.1+) 皆內建支援 `
#include <tuple>
#include <string>
std::tuple<int, double> t(1, 3.14); // 直接初始化
std::tuple<std::string, int*> u; // 預設初始化: ("", nullptr)
auto v = std::make_tuple("hello", 42); // 型別推導: tuple<const char*, int>
// 元素個數
constexpr size_t sz = std::tuple_size<decltype(t)>::value; // 2
// 第 N 個元素型別 (0-based)
using FirstType = std::tuple_element<0, decltype(t)>::type; // int
int n = std::get<0>(t); // 讀取第一個元素 (1)
std::get<1>(t) = 2.71; // 修改第二個元素
// std::get<2>(t); // ❌ 編譯錯誤:越界
C++ 函數只能返回單一值。傳統做法定義多個函數或輸出參數,語意不清。Tuple 完美封裝:
// 傳統:分離函數
int open_file(const char* path);
FILE* open_file_ptr(const char* path);
// Tuple 方案:單一函數返回多值
using FileResult = std::tuple<int, FILE*>;
FileResult open_file(const char* path) {
// ... 實作 ...
return std::make_tuple(fd, fp);
}
// 使用:結構化綁定 (C++17)
auto [fd, fp] = open_file("data.txt"); // 直接解包
if (fd >= 0) { /* 使用 fp */ }
面向物件環境可進一步封裝為 `fstream` 衍生類別。
避免浮點誤差,用兩個整數表示貨幣 (元、分/菲爾斯)。傳統用 `struct` 需手寫比較運算子,Tuple 已內建字典序比較:
using Currency = std::tuple<long long, int>; // (主要單位, 次要單位)
class USD {
Currency curr_;
public:
explicit USD(long long d=0, int c=0) : curr_(d, c) {}
// 介面不變,內部實現變更對使用者透明
bool operator==(const USD& other) const { return curr_ == other.curr_; }
bool operator<(const USD& other) const { return curr_ < other.curr_; }
// ... 其他比較運算子自動合成 (C++20 <=>) ...
};
比較範例:
Currency c1(100, 99), c2(100, 98), c3(100, 98);
bool eq = (c1 == c2); // false
eq = (c2 == c3); // true
// 底層逐元素比較:先比第一元素,相等再比第二...