Search code examples
c++boost

is it possible to add extra data to a struct in boost


Hello so if i have class like this

class Doors
{
private:
    friend class boost::serialization::access;
    template <class Ar>
    void serialize(Ar &ar, unsigned)
    {
        ar &username &password;
    }

public:
    string username;
    string password
};

and then i serialized the class and added it to MySql then later i decided to edit that struct and add some more data to it like this

class Doors
{
private:
    friend class boost::serialization::access;
    template <class Ar>
    void serialize(Ar &ar, unsigned)
    {
        ar &username &password &email &phone;
    }

public:
    string username;
    string password;
    string email;
    string phone;
};

now i already have some serialized data in MySql before editing the struct if i deserialize it it will show boost error because i have modified the struct now my question is

is it possible to take the old class then add the new data to it ? because i dont want to delete the old ones.


Solution

  • Notice the second argument to serialize() which you're not using, it's the class version.

    You can bump the class version and optionally read the additional fields depending on the version.

    class Doors
    {
    private:
        friend class boost::serialization::access;
        template <class Ar>
        void serialize(Ar& ar, unsigned version)
        {
            ar &username &password;
            if (version > 0) {
                ar &email &phone;
            }
        }
    
    public:
        string username;
        string password;
        string email;
        string phone;
    };
    
    BOOST_CLASS_VERSION(Doors, 1);
    

    The default version is 0. So your old format with no class version defined will have version 0.