1
默認情況下,在Boost.Serialization中,枚舉類型被序列化爲32位整數。但我需要序列化一些枚舉類型作爲不同的寬度整數。我試圖專門化boost :: serialization :: serialize方法,但它似乎不適用於枚舉。如何更改Boost.Serialization中的默認枚舉序列化
這裏是我的嘗試:
#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;
}
您可以將枚舉封裝在類中並序列化類嗎? – Dan
我認爲這也行不通。 –