擁有一個數組std::vector<BaseClass*>
使用Google協議緩衝區庫將此數組保存到文件的正確方法是什麼?如何使用Protocol Buffers將多態對象的數組序列化爲文件?
BaseClass
是類層次結構的基類,它有幾個子類。 Google的協議緩衝區是否適用於此目的,或者可能會優先使用其他庫?
擁有一個數組std::vector<BaseClass*>
使用Google協議緩衝區庫將此數組保存到文件的正確方法是什麼?如何使用Protocol Buffers將多態對象的數組序列化爲文件?
BaseClass
是類層次結構的基類,它有幾個子類。 Google的協議緩衝區是否適用於此目的,或者可能會優先使用其他庫?
如上所述,您必須使用擴展機制來實現多態。 此鏈接你可能會感興趣http://www.indelible.org/ink/protobuf-polymorphism/
協議緩衝區允許在您的代碼中像std::vector
這樣的重複字段。至於多態對象,你可以使用擴展框架。請參閱擴展標題下的here。
您可以創建一個列表消息MyList
其中包含Class
類型的元素。還有你需要一個特定的消息對於每個子類:
message MyList{
repeated Class entry = 1;
}
message Class{
required BaseProperties baseProperties = 1;
oneof{
SubClassOne sub_one_properties = 2;
SubClassTwo sub_two_properties = 3;
...
}
}
message BaseProperties{
//contains common properties of BaseClass
}
message SubClassOne{
//contains specific properties of one this SubClass
}
message SubClassTwo{
//contains specific properties of one this SubClass
}
如果你不喜歡oneof
關鍵字,或使用的是舊libprotobuf,還可以插入與typeinformations枚舉,並添加相應的可選messagefields:
message Class{
enum ClassType{
SUB_CLASS_ONE = 1;
SUB_CLASS_TWO = 2;
}
required ClassType type = 1;
required BaseProperties baseProperties = 2;
optional SubClassOne sub_one_properties = 3;
optional SubClassTwo sub_two_properties = 4;
...
}