mercredi 25 janvier 2017

Custom serialization of shared_ptr in cereal C++11 library

I am trying to achieve below customized JSON format for cereal shared_ptr.

For the x_sptr, class Test {

std::shared_ptr<X> x_sptr;
// std::string str;
}

Where X is, struct X { int x_int; std::string x_str;

    template<class A> void serialize(A& ar) {
    ar(CEREAL_NVP(x_int), CEREAL_NVP(x_str));
}
};

Current Implementation use this one,

"x_sptr": { "ptr_wrapper": { "id" : 2147483650, "data": { "x_int": 1, "x_str": "sptr_str" } } },

My expected implementation will look like below,

"x_sptr": { "x_int": 1, "x_str": "sptr_str" }

For me, its ok to have multiple objects with same values.

Can someone please guide me how to achieve this.

I have tried below code in memory.hpp, it is able to read JSON in the expected format, but corrupt the node values which will come after that shared_ptr variable. In our example, it is str variable in class Test which is commented.

//! Loading std::shared_ptr, case when no user load and construct for non     polymorphic types


    template <class Archive, class T> inline
    typename std::enable_if<!std::is_polymorphic<T>::value, void>::type
    CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::shared_ptr<T> & ptr )
    {
      // JFT 
        std::cout << " CEREAL_LOAD_FUNCTION_NAME ptr_wrapper 1 " << std::endl;
        auto ptrw = memory_detail::make_ptr_wrapper( ptr ) ;
      // std::cout << "CEREAL_LOAD_FUNCTION_NAME 2 " << std::endl;
      auto & ptr2 = ptrw.ptr; 
     ptr2.reset( detail::Construct<T, Archive>::load_andor_construct() );
    //    ar( CEREAL_NVP_("data", *ptr2) );
    ar(*ptr2);

    // ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( ptr ))    );
    //const T * t = ptr.get();
    //ar(CEREAL_NVP(t));
    }

Thanks, Abhishek

Aucun commentaire:

Enregistrer un commentaire