1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include <iostream> using namespace std; template<int IDX, int MAX, typename... Args> struct PRINT_TUPLE { static void print(ostream& os, const tuple<Args...>& t) { os << get<IDX>(t) << (IDX + 1 == MAX ? "" : ","); PRINT_TUPLE<IDX + 1, MAX, Args...>::print(os, t); } }; template<int MAX, typename... Args> struct PRINT_TUPLE<MAX, MAX, Args...> { static void print(std::ostream& os, const tuple<Args...>& t) { } }; template<typename... Args> ostream& operator<<(ostream& os, const tuple<Args...>& t) { os << "["; PRINT_TUPLE<0, sizeof...(Args), Args...>::print(os, t); return os << "]"; } int main() { int ref1 = 1; tuple<int, string> a{ ref(ref1),"a" }; auto b = make_tuple(2, "b", 2.2); get<1>(b) = "bbb";
int x; string y; tie(x, y) = a; cout << "提取元素" << endl; cout << "a 中的元素:" << x << " " << y << endl; tie(x, y, ignore) = b; cout << "b 中的元素:" << x << " " << y << endl << endl;
cout << "简易的交换元素" << endl; string t = get<1>(a); cout << "t:" << t << endl; get<1>(a) = get<1>(b); get<1>(b) = t.c_str(); cout << "get<1>(a):" << get<1>(a) << endl; cout << "get<1>(b):" << get<1>(b) << endl << endl;
cout << "查询 tuple 的大小:" << endl; cout << "a 的大小:" << tuple_size<decltype(a)>::value << endl; cout << "b 的大小:" << tuple_size<decltype(b)>::value << endl << endl; tuple_element<0, decltype(a)>::type t1 = get<0>(a); auto t2 = get<0>(a); cout << t1 << " " << t2 << endl << endl;
tuple<int, int, string> c{ 1,1,"1" }; pair<int, string> d{ 2,"2" }; auto e = tuple_cat(c, d); cout << "e 中的元素:"; cout << e;
return 0; }
|