我有一个 MyFile.hpp 头文件,其中包含各种类型和枚举。我如何对给定的示例代码进行序列化/反序列化。
//我的文件.hpp
namespace A {
namespace B {
typedef std::string MyString;
typedef std::map<std::string,std::string> my_type;
typedef bool result;
struct MyTimer
{
int time;
private :
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & time;
}
};
enum MODE
{
Sleep=1,
HybridSleep,
Hybernate
}
}
}
我需要在相应的 MyFile.cpp 中进行实现,但不知道如何进行。
谢谢,
最佳答案
map 、字符串等可以通过包含相关的 header 来序列化:
#include <boost/serialization/map.hpp>
#include <boost/serialization/string.hpp>
枚举 counts as a primitive type:
A type T is Serializable if and only if one of the following is true:
it is a primitive type.
By primitive type we mean a C++ built-in type and ONLY a C++ built-in type. Arithmetic (including characters), bool, enum are primitive types. Below in serialization traits, we define a "primitive" implementation level in a different way for a different purpose. This can be a source of confusion.
- It is a class type and one of the following has been declared according to the prototypes detailed below:
- a class member function serialize
- a global function serialize
- it is a pointer to a Serializable type.
- it is a reference to a Serializable type.
- it is a native C++ Array of Serializable type.
对于更棘手的情况,有 BOOST_STRONG_TYPEDEF
(参见 documentation "Serialization Wrappers")
关于c++ - boost 使用 struct 中包含的 typedef 定义的 native 类型的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22533863/