Boost Serialization using polymorphic archives

前端 未结 2 1345
臣服心动
臣服心动 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: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  
        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  
        void serialize(Archive & ar, const unsigned int file_version) {  
            ar & boost::serialization::base_object(*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 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 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(b2.get()))->data2 << endl;  
    
        return 0;  
    }  
    

提交回复
热议问题