can we separate the main serialize method in different class to make it easier and less complex using boost libraries for c++?

若如初见. 提交于 2019-12-12 06:48:13

问题


how to separate the serialize method from this code and encapsulate it to a another class so that we don't have to write it in every class we create.

class Test  
{  
private:      
    friend class boost::serialization::access;  
   template<class Archive> void serialize(Archive & ar,  
            const unsigned int version)   
    {  
        ar & BOOST_SERIALIZATION_NVP(a);  
        ar & BOOST_SERIALIZATION_NVP(b);  
        ar & BOOST_SERIALIZATION_NVP(emp); 
    }  

    int a; 
    int b; 
    Employee *emp; 
public:  
    Test(int a, int b,int c, int d)  
    { 
         this->a = a; 
         this->b = b; 
        emp = new Employee(c,d); 
    }  
}; 

回答1:


As written in the docs you can use a free function to serialize a class. Of course this requires the data members to be public.

For "real" classes that hide their data you could define a "serialization struct" that gets passed in and out of the real class for serialization purposes.



来源:https://stackoverflow.com/questions/22603039/can-we-separate-the-main-serialize-method-in-different-class-to-make-it-easier-a

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