2013-09-29 38 views
2

假設我有一個類A,其中包含一個私人成員B const * p,可通過公共職能B const& A::get()訪問。如何序列化函數A使用boost save_construct_dataload_construct_data函數?如何通過getter函數序列化包含指針的類?

這裏是我的包含嘗試(請注意,這個例子說明這個問題本身,而不是原因爲什麼我用這get功能):

#include <boost/archive/text_iarchive.hpp> 
#include <boost/archive/text_oarchive.hpp> 

#include <fstream> 

class B 
{ 
public: 
    int a; 

     ////////////////////////////////// 
     // Boost Serialization: 
     // 
    private: 
     friend class boost::serialization::access; 
     template<class Archive> 
     void serialize(Archive & ar,const unsigned int file_version) 
     { 
      ar & a; 
     } 
}; 

class A 
{ 
public: 
    A(B const * p) : p(p) {} 
    B const& get() const {return *p;} 
private: 
    B const * p; 

    void A::Save(char * const filename); 
    static A * const Load(char * const filename); 

     ////////////////////////////////// 
     // Boost Serialization: 
     // 
    private: 
     friend class boost::serialization::access; 
     template<class Archive> 
     void serialize(Archive & ar,const unsigned int file_version){} 
}; 

namespace boost 
{ 
    namespace serialization 
    { 
     template<class Archive> 
     inline void save_construct_data(
     Archive & ar, A const * t, unsigned const int file_version 
     ) 
     { 
      ar << &t->get(); 
     } 

     template<class Archive> 
     inline void load_construct_data(
     Archive & ar, A * t, const unsigned int file_version 
     ) 
     { 
      B const * p; 
      ar >> p; 

      ::new(t) A(p); 
     } 
    } 
} 

// save the world to a file: 
void A::Save(char * const filename) 
{ 
    // create and open a character archive for output 
    std::ofstream ofs(filename); 

    // save data to archive 
    { 
     boost::archive::text_oarchive oa(ofs); 

     // write the pointer to file 
     oa << this; 
    } 
} 

// load world from file 
A * const A::Load(char * const filename) 
{ 
    A * a; 

    // create and open an archive for input 
    std::ifstream ifs(filename); 

    boost::archive::text_iarchive ia(ifs); 

    // read class pointer from archive 
    ia >> a; 

    return a; 
} 

int main() 
{ 

} 

的錯誤是:error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const B *' (or there is no acceptable conversion)

回答

2

你不能序列化一個臨時的(AFAICT是Boost限制)。

B const * p = &t->get(); 
ar << p; 
+0

就是這樣,歡呼聲。 – arman

相關問題