且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问boost融合映射字段名称

更新时间:2023-02-18 23:24:22

#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);
}