简体   繁体   English

如何在Boost.Serialization中更改默认的枚举序列化

[英]How to change the default enums serialization in Boost.Serialization

By default in Boost.Serialization, enum types are serialized as a 32-bit integer. 在Boost.Serialization中,默认情况下,枚举类型被序列化为32位整数。 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. 我试图专门化boost :: serialization :: serialize方法,但是对于枚举似乎不起作用。

Here is my attempt: 这是我的尝试:

#include <iostream>
#include <boost/archive/binary_oarchive.hpp>
#include <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. 您可以通过对包含MyEnum_t的任何对象进行序列化以转换为char来完成所需的操作。 You could also do what Dan suggested and encapsulate the enum in a first-class type for which you can overload the serialization. 您还可以按照Dan的建议进行操作,并将枚举封装为一流的类型,从而可以重载序列化。 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. 内部表示似乎是存档的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM