为std::tuple增加格式化/序列化能力

转载请注明出处。谢谢

C++11中有很多激动人心的特性,但是相应的使得C++更加复杂。。。
新标准还修改了原有标准库,并增加了很多内容。

在学习新标准的过程中动手写了个 为std::tuple增加格式化/序列化能力的一小段代码

#define  DECLARE_TUPLE_SERIALIZATION_FUNCTION(FUNC_NAME,BEG,SEP,END)     \
namespace  sjdfsjfyttsaihfah6755jsdf554433356sdf{                        \
template 
< typename Tuple,std::size_t N >                                  \
struct  tuple_printer                                                    \
{                                                                       \
    
static   void  print(std::ostream &  os, const  Tuple &  t)                  \
    {                                                                   \
        os
<< std:: get < std::tuple_size < Tuple > ::value  -  N  > (t) << SEP;       \
        tuple_printer
< Tuple,N - 1 > ::print(os,t);                          \
    }                                                                   \
};                                                                      \
                                                                        \
template 
< typename Tuple >                                                \
struct  tuple_printer < Tuple, 1 >                                            \
{                                                                       \
    
static   void  print(std::ostream &  os, const  Tuple &  t)                  \
    {                                                                   \
        os
<< std:: get < std::tuple_size < Tuple > ::value - 1 > (t);               \
    }                                                                   \
};                                                                      \
}                                                                       \
template 
< typename Tuple >                                                \
void  FUNC_NAME(std::ostream &  os, const  Tuple &  t)                         \
{                                                                       \
    os
<< BEG;                                                            \
    sjdfsjfyttsaihfah6755jsdf554433356sdf::tuple_printer
< Tuple,std::tuple_size < Tuple > ::value > ::print(os,t);    \
    os
<< END;                                                            \
}                                                                       
实现成宏是为了使用起来更方便,可以随意指定 函数名 前缀 分隔符 和 后缀。
使用方法如下:

DECLARE_TUPLE_SERIALIZATION_FUNCTION(serialize_tuple, " < " , "  ,  " , " > " )

int  main()
{
    
int  i = 10 ;
    auto a 
=  std::make_tuple( 3 , " lala " ,i, ' c ' );
    serialize_tuple(std::cout,a);
}

输出为:
<3 , "lala" , 10 , c>

测试环境为GCC 4.5,注意编译时候请打开C++0X支持。

转载于:https://my.oschina.net/u/90679/blog/109039

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值