我一直在尝试使用一些boost融合的东西来写一个常规的c结构文件.一个
XML文件似乎是捕获数据并使其与其他工具兼容或手动编辑的好方法.似乎我几乎拥有,但似乎缺少一些基本的东西.
我正在使用与boost :: fusion快速入门页面相似的东西: http://www.boost.org/doc/libs/1_54_0/libs/fusion/doc/html/fusion/quick_start.html.作为一个附注,我已经彻底地看了这里和boost的文档,但没有人似乎正在访问字段名称.
我正在使用与boost :: fusion快速入门页面相似的东西: http://www.boost.org/doc/libs/1_54_0/libs/fusion/doc/html/fusion/quick_start.html.作为一个附注,我已经彻底地看了这里和boost的文档,但没有人似乎正在访问字段名称.
struct print_xml
{
template <typename T>
void operator()(T const& x) const
{
std::cout
<< '<' << x.first << '>'
<< x
<< "</" << x.first << '>'
;
}
};
我想使用它如下:
BOOST_FUSION_ADAPT_STRUCT(
myStructType,(double,val1)
(double,val2)
(char,letter)
(int,number)
)
myStructType saveMe = { 3.4,5.6,'g',9};
for_each(saveMe,print_xml());
其他时候我将结构定义如下,但还是没有运气:
namespace fields{
struct val1;
struct val2;
struct letter;
struct number;
}
typedef fusion::map<
fusion::pair<fields::val1,double>,fusion::pair<fields::val2,fusion::pair<fields::letter,char>,fusion::pair<fields::number,int> > myStructType;
我知道没有成员第一,但它真的好像应该是为了访问字段名称!代码我已经很好用x.second,但是没有完成我需要的是获取字段名称.
我该怎么办呢?
谢谢!
解决方法
#include <iostream>
#include <string>
#include <boost/mpl/range_c.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/zip.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/mpl.hpp>
namespace fusion=boost::fusion;
namespace mpl=boost::mpl;
struct myStructType
{
double val1;
double val2;
char letter;
int number;
};
BOOST_FUSION_ADAPT_STRUCT(
myStructType,number)
)
template <typename Sequence>
struct XmlFieldNamePrinter
{
XmlFieldNamePrinter(const Sequence& seq):seq_(seq){}
const Sequence& seq_;
template <typename Index>
void operator() (Index idx) const
{
//use `Index::value` instead of `idx` if your compiler fails with it
std::string field_name = fusion::extension::struct_member_name<Sequence,idx>::call();
std::cout
<< '<' << field_name << '>'
<< fusion::at<Index>(seq_)
<< "</" << field_name << '>'
;
}
};
template<typename Sequence>
void printXml(Sequence const& v)
{
typedef mpl::range_c<unsigned,fusion::result_of::size<Sequence>::value > Indices;
fusion::for_each(Indices(),XmlFieldNamePrinter<Sequence>(v));
}
int main()
{
myStructType saveMe = { 3.4,9};
printXml(saveMe);
}