2

假设我有一个类A,它包含一个私有成员B const * p,可以通过公共函数访问B const& A::get()。如何序列化函数 A 使用 boostsave_construct_dataload_construct_data函数序列化函数 A?

这是我包含的尝试(请注意,此示例说明了问题本身,而不是我使用此功能的原因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)

4

1 回答 1

2

您不能序列化临时的(AFAICT 是 Boost 限制)。

B const * p = &t->get();
ar << p;
于 2013-09-29T15:54:23.367 回答