#include <iostream> #include <utility> #include <tuple> #include <complex> #include <string> using namespace std; // 代码 改编自 C++标准库——自学教程与参考手册 英文第二版 //==================================== // tuple io template <int IDX,int MAX,typename... Args> struct PRINT_TUPLE{ static void print(ostream& strm, const tuple<Args...>& t){ strm << get<IDX>(t) << (IDX + 1 == MAX ? "" : ","); PRINT_TUPLE<IDX + 1, MAX, Args...>::print(strm,t); } }; template <int MAX,typename... Args> struct PRINT_TUPLE<MAX, MAX, Args...>{ static void print(ostream& strm, const tuple<Args...>& t){ } }; template <typename... Args> ostream& operator << (ostream& strm, tuple<Args...>& t) { strm << "["; PRINT_TUPLE<0, sizeof...(Args), Args...>::print(strm,t); return strm << "]"; } //==================================== class Foo{ public: Foo(tuple<int, float>){ cout << "Foo::Foo(tuple)" << endl; } template <typename... Args> Foo(Args... args){ cout << "Foo::Foo(atgs...)" << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { // cpp11 后 一些新语法 在STL中得使用 tuple<int, double>t(1,2.22); pair<int, Foo>p1(42, t); pair<int, Foo>p2(piecewise_construct, make_tuple(42), t); // 使用 ref() 表示对变量的引用 int i = 0; auto p = make_pair(ref(i), ref(i)); // 创建 pair<int&,int&> ++p.first; ++p.second; cout << "i = " << i << endl; // tie() 演示 pair<char, char> q = make_pair(‘c‘,‘b‘); char c; tie(ignore, c) = q; // char c == ‘b‘ // tuple<string, int, int, complex<double>> tt; tuple<int, double,string> t1(41,6.3,"nico"); cout << get<0>(t1) << " "; cout << get<1>(t1) << " "; cout << get<2>(t1) << " "; cout << endl; auto t2 = make_tuple(22,44,"nico"); get<1>(t1) = get<1>(t2); t1 = t2; // tuple io tuple <int, double, string> iot(77, 1.1, "more light"); cout << "io: " << iot << endl; return 0; }
cpp11stl的例子 VS2013下编译 通过
时间: 2024-11-05 15:49:24