打印元组

元组中存储任意数理任意类型的值,包括元组类型本身。元组有固定的大小和固定的值类型,这些都是在编译时确定的。然而,元组没有提供任何内置的机制来遍历其元素。这个例子通过模板元编程来打印一个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))))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值