[英]How to serialize an array of polymorphic objects to file using Protocol Buffers?
Having an array std::vector<BaseClass*>
what is the correct way of saving this array to a file using Google's Protocol Buffers library? 有一个数组
std::vector<BaseClass*>
使用Google的Protocol Buffers库将这个数组保存到文件的正确方法是什么?
BaseClass
is a base class of hierarchy of classes, it has several sub classes. BaseClass
是类的层次结构的基类,它有几个子类。 Is Google's Protocol Buffers even suitable for this purpose or maybe another library would be preferred? 谷歌的协议缓冲区是否适用于此目的,或者可能首选其他库?
You could create a list-message MyList
which contains elements of type Class
. 您可以创建一个列表消息
MyList
,其中包含Class
类型的元素。 And there you need a specific message for each subclass: 在那里,您需要为每个子类提供特定的消息:
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
}
If you don't like the oneof
keyword, or are using an older libprotobuf, you can also insert an enum with typeinformations and add corresponding optional messagefields: 如果你不喜欢
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;
...
}
As it said above, you have to use extension mechanism to implement polymorphism. 如上所述,您必须使用扩展机制来实现多态。 This link you may find useful http://www.indelible.org/ink/protobuf-polymorphism/
您可以找到有用的链接http://www.indelible.org/ink/protobuf-polymorphism/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.