std::tuple(C++11)是**異構固定大小集合**,適用於:函數多返回值、參數包傳遞、編譯期數據結構、元編程。
// 直接初始化
std::tuple<int, double, std::string> t1(42, 3.14, "hello");
// make_tuple:類型推導(會衰減數組/函數)
auto t2 = std::make_tuple(42, 3.14, "hello"); // tuple
// tie:創建引用元組,用於解包
int a; double b; std::string c;
std::tie(a, b, c) = t1; // 解包賦值
std::tie(std::ignore, b, std::ignore) = t1; // 忽略部分
// 編譯期常量索引(必須為常量表達式)
auto v0 = std::get<0>(t1); // int
auto v1 = std::get<1>(t1); // double
auto v2 = std::get<2>(t1); // string
// C++14:按類型獲取(類型唯一時)
auto v0b = std::get<int>(t1); // 僅當 tuple 中 int 唯一
// 結構化綁定(C++17,最推薦)
auto [x, y, z] = t1; // x=int, y=double, z=string
constexpr size_t n = std::tuple_size_v<decltype(t1)>; // 3
using FirstType = std::tuple_element_t<0, decltype(t1)>; // int
std::get<I>(t) 要求 `I` 為編譯期常量,無法用運行期變量索引 → **無法用普通迴圈遍歷**。
template <size_t I = 0, typename Tuple, typename F>
void for_each_impl(Tuple& t, F f) {
if constexpr (I < std::tuple_size_v<Tuple>) {
f(std::get<I>(t));
for_each_impl<I+1>(t, f);
}
}
template <typename Tuple, typename F>
void for_each(Tuple& t, F f) { for_each_impl<0>(t, f); }
// 使用
for_each(t1, [](auto& x) { std::cout << x << ' '; });
std::apply([](auto&... args) { (std::cout << ... << args) << '\n'; }, t1);
// 或配合 fold expression
std::apply([](auto&... args) { ((std::cout << args << ' '), ...); }, t1);
待標準反射(C++26 預期)成熟前,std::apply 是標準庫標準解法。
| 場景 | 推薦 |
|---|---|
| 函數返回 2-3 個相關值 | std::tuple / std::pair / 結構化綁定 |
| 返回值有明確業務含義 | **自定義 struct**(語義清晰、可擴展、可加方法) |
| 編譯期異構序列、元編程 | std::tuple / `std::integer_sequence` |
| 運行期動態異構容器 | std::variant / `std::any` / 多態基類指標 |
std::tuple 是**編譯期異構聚合**的利器,善用結構化綁定與 `std::apply`,避免濫用於運行期業務建模。