元组中存储任意数理任意类型的值,包括元组类型本身。元组有固定的大小和固定的值类型,这些都是在编译时确定的。然而,元组没有提供任何内置的机制来遍历其元素。这个例子通过模板元编程来打印一个C++11的std::tuple中的各个元素。(参考自:Marc Gregoire等,C++高级编程(第二版),清华大学出版社,P661)
代码如下:
#include<iostream>
#include<tuple>
#include<string>
using namespace std;
template<int n,typename T>
class tuple_print_helper {
public:
tuple_print_helper(T t) {
tuple_print_helper<n - 1, T> tp(t);
cout << ",";
tuple_print(get<n - 1>(t));
}
};
template<typename T>
class tuple_print_helper<0, T>
{
public:
tuple_print_helper(T t){}
};
template<typename T>
class tuple_print_helper<1, T>
{
public:
tuple_print_helper(T t) {
cout << "(";
tuple_print(get<0>(t));
}
};
template<typename T>
void tuple_print(T t) {
tuple_print_helper<tuple_size<T>::value, T> tph(t);
cout << ")";
}
template<>
void tuple_print<int>(int t) {
cout << t;
}
template<>
void tuple_print<double>(double t) {
cout << t;
}
template<>
void tuple_print<char>(char t) {
cout << t;
}
template<>
void tuple_print<bool>(bool t) {
cout << t;
}
template<>
void tuple_print<const char *>(const char* t) {
cout << t;
}
template<>
void tuple_print<string>(string t) {
cout << t;
}
int main() {
string str = "YES";
auto t1 = make_tuple(make_tuple(32, str),4,"NO");
auto t2 = make_tuple(t1, t1, t1);
auto t3 = make_tuple(t2, t2, t2);
auto t4 = make_tuple(t3, t3, t3);
tuple_print(t4);
cout << endl;
}
输出结果:
(((((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO)),(((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO)),(((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO))),((((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO)),(((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO)),(((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO))),((((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO)),(((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO)),(((32,YES),4,NO),((32,YES),4,NO),((32,YES),4,NO))))