Learning Curve Plus Plus (LCPP)
cereal.h
Go to the documentation of this file.
1 /**
2  * @file cereal.h
3  * @author Ozgur Taylan Turan
4  *
5  * Custom Cereal serialization helpers.
6  *
7  * Cereal does not provide built-in support for some standard library types
8  * such as std::optional and std::filesystem::path.
9  * These save/load functions allow these types to be serialized and
10  * deserialized in a portable way by converting them into simpler
11  * serializable forms.
12  *
13  */
14 
15 #ifndef MY_CEREAL_H
16 #define MY_CEREAL_H
17 
18 namespace cereal {
19 
20 //-----------------------------------------------------------------------------
21 // Save: std::optional<T> by first storing whether it has a value,
22 // then storing the value if present.
23 //-----------------------------------------------------------------------------
24 template <class Archive, class T>
25 void save(Archive& ar, const std::optional<T>& opt)
26 {
27  bool hasVal = opt.has_value();
28  ar(CEREAL_NVP(hasVal));
29  if (hasVal)
30  {
31  const T& value = *opt;
32  ar(cereal::make_nvp("value", value));
33  }
34 }
35 
36 //-----------------------------------------------------------------------------
37 // Load: std::optional<T> by reading presence flag, then value if present.
38 //-----------------------------------------------------------------------------
39 template <class Archive, class T>
40 void load(Archive& ar, std::optional<T>& opt)
41 {
42  bool hasVal;
43  ar(CEREAL_NVP(hasVal));
44  if (hasVal)
45  {
46  T value;
47  ar(CEREAL_NVP(value));
48  opt = std::move(value);
49  }
50  else
51  {
52  opt = std::nullopt;
53  }
54 }
55 
56 //-----------------------------------------------------------------------------
57 // Save: std::filesystem::path as a string.
58 //-----------------------------------------------------------------------------
59 template <class Archive>
60 void save(Archive& ar, const std::filesystem::path& path)
61 {
62  ar(path.string());
63 }
64 
65 //-----------------------------------------------------------------------------
66 // Load: std::filesystem::path from a stored string.
67 //-----------------------------------------------------------------------------
68 template <class Archive>
69 void load(Archive& ar, std::filesystem::path& path)
70 {
71  std::string temp;
72  ar(temp);
73  path = std::filesystem::path(temp);
74 }
75 
76 } //namespace cereal
77 
78 #endif