2009-08-26 91 views
11

我想序列化/反序列化以下類:如何使用Boost.serialize序列化派生的模板類?

class Feature{ 
... 
virtual string str()=0; 
}; 

template<typename T> 
class GenericFeature : public Feature{ 
T value; 
... 
virtual string str(); 
}; 

我讀boost.serialize文檔和賽義德,你必須註冊類。 我可以在構造函數中註冊它們。但是加載會有問題,因爲註冊是動態的,而不是靜態的(據我所知,你必須在序列化/反序列化之前註冊類)。

如何保存/加載這些類的類?

回答

15

首先告訴提振該功能是抽象的,並不總是需要:

BOOST_SERIALIZATION_ASSUME_ABSTRACT(Feature); 

序列化方法應該或多或少是這樣的:

template<class Archive> 
void Feature::serialize(Archive & ar, const unsigned int version) 
{ 
    ar & BOOST_SERIALIZATION_NVP(some_member); 
} 


template<typename T,class Archive> 
void GenericFeature<T>::serialize(Archive & ar, const unsigned int version) 
{ 
    ar & boost::serialization::base_object<Feature>(*this); //serialize base class 
    ar & BOOST_SERIALIZATION_NVP(some_other_member); 
} 

現在棘手的問題是註冊類在序列化/反序列化:

boost::archive::text_iarchive inputArchive(somesstream); 

boost::archive::text_oarchive outputArchive(somesstream); 

//something to serialize 
Feature* one = new GenericFeature<SomeType1>(); 
Feature* two = new GenericFeature<SomeType2>(); 
Feature* three = new GenericFeature<SomeType3>(); 

//register our class, must be all of posible template specyfication  
outputArchive.template register_type< GenericFeature<SomeType1> >(); 
outputArchive.template register_type< GenericFeature<SomeType2> >(); 
outputArchive.template register_type< GenericFeature<SomeType3> >(); 

// now simply serialize ;-] 
outputArchive << one << two << three; 

// register class in deserialization 
// must be the same template specification as in serialize 
// and in the same correct order or i'm get it wrong ;-D 
inputArchive.template register_type< GenericFeature<SomeType1> >(); 
inputArchive.template register_type< GenericFeature<SomeType2> >(); 
inputArchive.template register_type< GenericFeature<SomeType3> >(); 

Feature* another_one; 
Feature* another_two; 
Feature* another_three; 

// and deserialize ;-] 
inputArchive >> another_one >> another_two >> another_three; 

如果你需要隱藏明確登記somewh並且使它更加自動化,有一種想法是製作特殊的函子模板,它註冊一個派生類,創建所有可用類並放入一個列表中,Feature類的一個靜態方法將它們全部註冊。然而問題是你需要註冊所有版本的檔案,現在我不知道多態檔案是否能夠完成這項工作。

+0

我認爲第一個代碼框的第11行有一個錯誤。如果我沒有弄錯,你應該在「boost :: serialization :: base_object」的左邊有「ar&」。雖然很好的答案! – 2010-11-18 01:21:18

+3

@lionbest:你不應該使用'BOOST_SERIALIZATION_BASE_OBJECT_NVP'而不是'boost :: serialization :: base_object (* this);' – Cookie 2011-08-22 10:23:08

+0

我想你可能想要指定名稱,如果你有多個基類。我不認爲這個宏需要在這裏,但確定你可能想要一個。 – Arpegius 2011-08-23 09:30:53