|
Boost Users : |
Subject: Re: [Boost-users] How to change the default enums serialization inBoost.Serialization
From: Robert Ramey (ramey_at_[hidden])
Date: 2011-10-04 13:03:09
Andrés Senac wrote:
> Hi,
> 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 <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;
> }
>
>
> Thanks in advance,
> Andrés
Consider making a wrapper for you enum - like this;
struct enum_wrapper {
unsigned char m_value;
enum_wrapper(unsigned int value) :
m_value(value)
{
assert(value <= 255);
}
template<class Archive>
void save(Archive &ar, unsigned int version){
ar << m_value;
}
void load
...
}
then you can use
....
enum {
a
b
..
} e;
ar & enum_wrapper(e);
..
Robert Ramey
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net