1.tuple使用
(1)create a four-element tuple tuple<string, int, int, complex<double> >t;
(2)create and initialize a tuple explicitly tuple<int, float, string> t1(41, 6.3, "nico");
(3)create tuple with make_tuple auto t2 = make_tuple(22, 44, "stney");
tuple<int, int, string> t3 = make_tuple(22, 44, "stney");
(4)assign second value in t2 to t1 get<1>(t1) = get<1>(t2);
(5)compare value for value t1 < t2
(6)assigns value for value t1 = t2;
(7)assigns values of to 1,f,and s tie(i1, f1, s1) = t4;
#include <iostream>
#include <complex>
#include <tuple>
using namespace std;
int main() {
cout << "string,sizeof= " << sizeof(string) << endl;
cout << "double,sizeof= " << sizeof(double) << endl;
cout << "float,sizeof= " << sizeof(float) << endl;
cout << "int,sizeof= " << sizeof(int) << endl;
cout << "complex<double>,sizeof= " << sizeof(complex<double>) << endl;
tuple<string, int, int, complex<double> >t;
cout << "sizeof= " << sizeof(t) << endl;
tuple<int, float, string> t1(41, 6.3, "nico");
cout << "tuple<int, float, string>,sizeof= " << sizeof(t1) << endl;
cout << "t1: " << get<0>(t1) << ' ' << get<1>(t1) << ' ' << get<2>(t1) << endl;
auto t2 = make_tuple(22, 44, "stney");
tuple<int, int, string> t3 = make_tuple(22, 44, "stney");
get<1>(t1) = get<1>(t2);
if(t1 < t2) {
cout << "t1 < t2" << endl;
} else {
cout << "t2 >= t1" << endl;
}
t1 = t2;
cout << "t1: " << get<0>(t1) << ' ' << get<1>(t1) << ' ' << get<2>(t1) << endl;
tuple<int, float, string> t4(77, 1.1, "more light");
int i1;
float f1;
string s1;
tie(i1, f1, s1) = t4;
cout << "i1= " << i1 << endl;
cout << "f1= " << f1 << endl;
cout << "s1= " << s1 << endl;
typedef tuple<int, float, string> TupleType;
cout << tuple_size<TupleType>::value << endl;
tuple_element<1, TupleType>::type f = 1.0;
typedef tuple_element<1, TupleType>::type T;
return 0;
}
2.tuple实现
#include <iostream>
using namespace std;
template<typename... Values> class Tuple;
template<> class Tuple<> {};
//递归继承
template<typename Head, typename... Tail>
class Tuple<Head, Tail...>
:private Tuple<Tail...>
{
typedef Tuple<Tail...> inherited;
protected:
Head m_head;
public:
Tuple() {}
Tuple(Head v,Tail... vtail):m_head(v),inherited(vtail...) {}
//typename Head::type head() { return m_head; }
//auto head()->decltype(m_head) { return m_head; }
Head head() { return m_head; }
inherited &tail() { return *this; }
};
int main() {
Tuple<int, float, string> t(41, 6.3, "nico");
cout << "int: " << sizeof(int) << endl;
cout << "float: " << sizeof(float) << endl;
cout << "char[]: " << sizeof("nico") << endl;
cout << "size: " << sizeof(t) << endl;
cout << t.head() << endl;
cout << t.tail().head() << endl;
cout << t.tail().tail().head() << endl;
return 0;
}