Accessing boost fusion map field name

删除回忆录丶 提交于 2019-11-29 03:45:42
cv_and_he
#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,
    (double, val1)
    (double, val2)
    (char, letter)
    (int, 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, 0, fusion::result_of::size<Sequence>::value > Indices; 
    fusion::for_each(Indices(), XmlFieldNamePrinter<Sequence>(v));
}

int main()
{
    myStructType saveMe = { 3.4, 5.6, 'g', 9};
    printXml(saveMe);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!