爲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支持。
相關文章
相關標籤/搜索