How to boost::serialize an std/boost::optional?

How can I serialize a class (with boost::serialization) that contains a boost::optional?

I.e. the following code will give an error when instantiated.

error C2039: 'serialize' : is not a member of 'boost::optional' C:\boost\boost_1_55_0\boost\serialization\access.hpp 118

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

class MyClass {
private:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & my_member;
    }

    boost::optional<int> my_member;
};

int main() {
    std::ofstream ofs("filename.txt");
    const MyClass g;
    boost::archive::text_oarchive oa(ofs);
    oa << g;
    return 0;
}

I understand there's probably a deeper question involved (what should you write to the file when the value is not present?), but there must be some standard solution for it. I am looking for the most simple way to solve this.

Answers


For boost::optional you just need to add #include <boost/serialization/optional.hpp>

It implements a non-member serialize function that will allow you to serialize boost::optional without worrying about the details.

Under the hood it first saves/loads the boolean value of t.is_initialized() and depending on its value decides if to save/load the rest.

You can see the source code here: http://www.boost.org/doc/libs/1_56_0/boost/serialization/optional.hpp


Need Your Help

Apply URL Withe List to restrict the internet

network-programming

I want to create an app to block all the webpages (http, optional https) in every Browser (so it has to be in a connection level, rather than a application level) except the ones in my white list.

How to stop Javascript from repeating the function?

javascript jquery

Guys I have a javascript which has a each loop in which I am calling a particular function for each index value. This script executes on mouse scroll event upon reaching page end (lazy loading).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.