Search code examples
c++boostreferenceboost-serialization

How to get value from reference in c++


I have a func which returns a const& to an Object. Let say,

class Y {
    private:
        Id id;
    public:
        Id const& GetId() const;
}  

Now this Y Object is part of another class, let say class X, which needs to be serialized by boost.

class X {
    template <class Archive>
    void serialize(Archive& ar, uint32 version)
     {
         ar & y->GetId();
     }
     Y y;
}

However, boost complains about this and gives error:

error C2027: use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'


C:\Users\Y.h(580) : see reference to function template instantiation 'Archive &boost::archive::detail::interface_iarchive<Archive>::operator &<const Id>(T &)' being compiled
            with
            [

How can I serialize the Id?


Solution

  • The purpose of boost serialization is to use references to serialize to an Archive.

    Problem is it receives the values as references and not CONST references.

    Id const& GetId() const; // Returns a const reference
    

    Try using the following

    Id & GetId(); 
    

    And then one of the following

    ar & y.GetId();
    ar << y.GetId();
    

    If you don't like the breaking of encapsulation then either use protected, friends, or copy it to another value and pass the value as reference

    Id copy = y.GetId();
    ar & copy;