开发者

How to change the default enums serialization in Boost.Serialization

开发者 https://www.devze.com 2023-04-10 00:06 出处:网络
By default in Boost.Serialization, enum types are serialized as a 32-bit integer. But I need to serialize some enum types as different width integer. I\'ve tried to specialize the boost::serialization

By default in Boost.Serialization, enum types are serialized as a 32-bit integer. But I need to serialize some enum types as different width integer. I've tried to specialize the boost::serialization::serialize method, but it seems it doesn't work for enums.

Here is my attempt:

#include <iostream>
#include <boost/archive/binary_oarchive.hpp>
#include 开发者_JS百科<boost/asio.hpp>

enum MyEnum_t
{
    HELLO, BYE
};

namespace boost 
{ 
namespace serialization
{

template< class Archive >
void save(Archive & ar, const MyEnum_t & t, unsigned int version)
{
    unsigned char c = (unsigned char) t;
    ar & c;
}

template< class Archive >
void load(Archive & ar, MyEnum_t & t, unsigned int version)
{
    unsigned char c;
    ar & c;
    t = (MyEnum_t) c;
}

} // namespace serialization
} // namespace boost

BOOST_SERIALIZATION_SPLIT_FREE(MyEnum_t)

int main(int argc, const char *argv[])
{
    boost::asio::streambuf buf;
    boost::archive::binary_oarchive pboa(buf); 

    buf.consume(buf.size()); // Ignore headers

    MyEnum_t me = HELLO;
    pboa << me;

    std::cout << buf.size() << std::endl; // buf.size() = 4, but I want 1

    return 0;
} 


This probably doesn't work because enums aren't a real type, I don't think you can in general overload a function for a specific enum.

You could accomplish what you want by doing the conversion to char in the serialization of whatever object contains your MyEnum_t. You could also do what Dan suggested and encapsulate the enum in a first-class type for which you can overload the serialization. Something like:

class MyEnum_clone {
  unsigned char v_;
  MyEnum_clone(MyEnum_t v) : v_(v) {};
  operator MyEnum_t() const {return MyEnum_t(v_); };

  // serialization...
};

That still likely won't be completetely transparent, though.

However, I don't see why you care about how the type is serialized. Isn't the point of serializing that you don't have to care about the internal representation of the serialization, as long as you can restore the object correctly. The internal representation seems like a property of the archive.

0

精彩评论

暂无评论...
验证码 换一张
取 消