As always with Boost Serialization, to customize the treatment of user-defined types you'd need to implement the customization point which is either member serialize/load/save
or free function serialize/load/save
(looked up by ADL).
Since member functions are not an option for enums, you'd need to supply an overload of, e.g., serialize
for your type. Sadly there is no way to get a generic implementation of that to be "better" than the predefined overloads for builtin primitive types.
Here's what would comes close (but it doesn't work 1):
namespace boost { namespace serialization {
template <typename Ar, typename T>
typename std::enable_if<std::is_enum<T>::value, void>::type
serialize(Ar& ar, T& e, unsigned)
{
ar & boost::serialization::make_binary_object(&e, sizeof(e));
}
} }
We can take the shortcut of "binary_object" serialization as we know by definition that enums have integral values as their underlying type, which makes them POD.
In the light of this - unfortunate - limitation, perhaps the best way is to manually call make_binary_object
as shown:
Live On Coliru
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <iostream>
#include <sstream>
using boost::serialization::make_binary_object;
enum class Example : uint8_t {
First = 1,
Second = 2,
};
int main() {
std::stringstream stream;
boost::archive::binary_oarchive ar(stream, boost::archive::no_header);
auto data = Example::First;
ar << make_binary_object(&data, sizeof(data));
std::cout << "Size: " << stream.str().size() << "
";
}
Which prints
Size: 1
as expected. You can use the make_binary_object
wrapper inside serialize
implementations and it will transparently take care of both serialization and deserialization.
See: Boost Serialization Wrappers in the Boost documentation
1 for similar reasons, BOOST_IS_BITWISE_SERIALIZABLE(Example)
will not work; I tested it
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…