答案是肯定的。这是一个完整的工作示例。我发明了一些简单的类型:
struct InstanceIdentity { int id; };
struct ClassLabel { std::string value; };
struct FeatureGroup { size_t count; };
使用非侵入式序列化:
namespace boost { namespace serialization {
template <typename Ar>
void serialize(Ar& ar, InstanceIdentity& ii, unsigned) { ar & ii.id; }
template <typename Ar>
void serialize(Ar& ar, ClassLabel& cl, unsigned) { ar & cl.value; }
template <typename Ar>
void serialize(Ar& ar, FeatureGroup& fg, unsigned) { ar & fg.count; }
} }
Instance 和 InstanceManager 类将它们的序列化方法作为成员(由于私有成员):
template <typename Ar>
void Instance::serialize(Ar& ar, unsigned) { ar & identity_ & class_label_ & features_; }
template <typename Ar>
void InstanceManager::serialize(Ar& ar, unsigned) { ar & instances_; }
Live On Coliru
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/access.hpp>
struct InstanceIdentity { int id; };
struct ClassLabel { std::string value; };
struct FeatureGroup { size_t count; };
class Instance
{
public:
Instance(){}
~Instance() = default;
//... a lot of functions here.
bool operator<(Instance const& other) const {
return identity_.id < other.identity_.id;
}
private:
InstanceIdentity identity_;
mutable ClassLabel class_label_;
mutable FeatureGroup features_;
friend class InstanceManager;
friend class boost::serialization::access;
template <typename Ar>
void serialize(Ar& ar, unsigned) { ar & identity_ & class_label_ & features_; }
};
class InstanceManager
{
public:
InstanceManager()
{
Instance a, b, c;
a.class_label_.value = "label a";
b.class_label_.value = "label b";
c.class_label_.value = "label c";
a.features_.count = 42;
b.features_.count = 24;
c.features_.count = -9;
a.identity_.id = rand();
b.identity_.id = rand();
c.identity_.id = rand();
instances_.insert(instances_.end(), a);
instances_.insert(instances_.end(), b);
instances_.insert(instances_.end(), c);
}
~InstanceManager() = default;
// a lot of functions here.
private:
std::set<Instance> instances_;
friend class boost::serialization::access;
template <typename Ar>
void serialize(Ar& ar, unsigned) { ar & instances_; }
};
namespace boost { namespace serialization {
template <typename Ar>
void serialize(Ar& ar, InstanceIdentity& ii, unsigned) { ar & ii.id; }
template <typename Ar>
void serialize(Ar& ar, ClassLabel& cl, unsigned) { ar & cl.value; }
template <typename Ar>
void serialize(Ar& ar, FeatureGroup& fg, unsigned) { ar & fg.count; }
} }
int main() {
InstanceManager im;
boost::archive::text_oarchive oa(std::cout);
oa << im;
}
打印
22 serialization::archive 12 0 0 0 0 3 0 0 0 0 0 846930886 0 0 7 label b 0 0 24 1681692777 7 label c 18446744073709551607 1804289383 7 label a 42