Boost Serialization using polymorphic archives

前端 未结 2 1323
臣服心动
臣服心动 2020-12-16 19:56

I am working on a client-server application that uses boost::serialization library for it\'s serialization needs.

I need to serialize and deserialize polymorphic o

相关标签:
2条回答
  • 2020-12-16 20:16

    Just a few comments...

    First, you can use the same operation to serialize and deserialize using a templated version:

    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
       ...
    }
    

    Also, instead of the macro, you can "configure" the archive to expect those types recognized as pointers:

    ar.register_type(static_cast<your_static_type_here *>(NULL));
    
    0 讨论(0)
  • 2020-12-16 20:37

    Found a resolution. I had to export the derived class with the statement:

    BOOST_CLASS_EXPORT(derived);
    

    Posting something that works with some corrections.

    using namespace std;  
    
    class base {  
      public:  
        int data1;  
    
        friend class boost::serialization::access;  
    
        template<typename Archive>  
        void serialize(Archive & ar, const unsigned int file_version) {  
            ar & data1;  
        }  
    
      public:  
        base() {};  
        base(int _d) : data1(_d) {}  
        virtual void foo() const {std::cout << "base" << std::endl;}  
    };  
    
    class derived : public base {  
      public:  
        int data2;  
    
        friend class boost::serialization::access;  
    
        template<typename Archive>  
        void serialize(Archive & ar, const unsigned int file_version) {  
            ar & boost::serialization::base_object<base>(*this);  
            ar & data2;  
        }  
    
      public:  
        derived() {};  
        derived(int _b, int _d) : base(_b), data2(_d) {}  
        virtual void foo() const {std::cout << "derived" << std::endl;}  
    };  
    
    BOOST_CLASS_EXPORT(derived);  
    
    int main(int argc, char *argv[]) {  
        // client  
        // Assign to base type  
        std::unique_ptr<const base> b1(new derived(1, 2));  
    
        std::ostringstream oss;  
        boost::archive::text_oarchive oa(oss);  
        oa & b1.get();   
    
        // server  
        // Retrieve derived type from base  
        std::unique_ptr<base> b2;
    
        std::istringstream iss(oss.str());
        boost::archive::text_iarchive ia(iss);
        {
            base *temp; 
            ia & temp;
            b2.reset(temp);
        }
        cout << b2->data1 << endl;  
        cout << (dynamic_cast<derived*>(b2.get()))->data2 << endl;  
    
        return 0;  
    }  
    
    0 讨论(0)
提交回复
热议问题