Boost fusion serialization of a class using BOOST_FUSION_ADAPT_ADT

一曲冷凌霜 提交于 2019-12-21 20:25:19

问题


I am trying to get a serialization module for classes using boost fusion. I have converted my class to a boost::fusion sequence. This example is followed from the slides of the talk of Michael Caisse at boostcon 13

https://github.com/boostcon/cppnow_presentations_2013/blob/master/thu/solving_world_problems_with_fusion.pdf?raw=true

The example explained by Michael worked good for struct type. The same could not be applied for class types. What am i missing here ?

#include <iostream>
#include <typeinfo>
#include <string>
#include <boost/fusion/include/sequence.hpp>
#include <boost/fusion/include/algorithm.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/adapt_adt.hpp>
#include <boost/fusion/include/is_sequence.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/type_traits.hpp> 

#include <vector>
#include <list>

using namespace std;

template< typename T >
void serialize(T v)
{
boost::fusion::for_each( v, (serial_out()) );
}

struct serial_out
{
template< typename T > 
void operator() ( T & v , typename std::enable_if<!boost::fusion::traits::is_sequence<T>::value>::type* = 0 ) const
{ 
    simple::serialize<T>::write(v); 
}

template< typename T > 
void operator() ( T & v , typename std::enable_if<boost::fusion::traits::is_sequence<T>::value>::type* = 0  ) const
{ 
    serialize(v); 
}

template< typename T >
void operator()( std::vector<T> & v ) const
{
    simple::serialize<int>::write(v.size());
    std::for_each(v.begin(),v.end(),*this);
}

template< typename T >
void operator()( std::list<T> & v ) const
{
    simple::serialize<int>::write(v.size());
    std::for_each(v.begin(),v.end(),*this);
}
};

namespace simple
{
template<typename T> struct serialize{};
template<> struct serialize<int>
{
    static void write(int v) { cout << v << endl; }
};
template<> struct serialize<float>
{
    static void write(float v) { cout << v << endl;  }
};
template<> struct serialize<std::string>
{
    static void write(std::string v)
    {
        cout << v << endl; 
    }
};
}


class secret_point
{
public:
secret_point(double x, double y) : x_(x), y_(y) {}
double get_x() const { return x_; }
void set_x(double d) { x_=d; }
double get_y() const { return y_; }
void set_y(double d) { y_=d; }
private:
double x_, y_;
};

BOOST_FUSION_ADAPT_ADT( secret_point, (double, double, obj.get_x(), obj.set_x(val) ) (double, double, obj.get_y(), obj.set_y(val) ) )

int main(int argc, char *argv[]) 
{
secret_point p(112,233);
serialize(p);

return 0;
}

来源:https://stackoverflow.com/questions/22943978/boost-fusion-serialization-of-a-class-using-boost-fusion-adapt-adt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!