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

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

those. The following code will throw an error when instantiating.

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 that there may be a deeper question (what should you write to the file when the value is missing?), But there must be some standard solution for this. I am looking for the easiest way to solve this problem.

+5
source share
1 answer

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

It implements a non-network serialization function that allows you to serialize boost::optional without worrying about the details.

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

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

+5
source

Source: https://habr.com/ru/post/1203487/


All Articles