简体   繁体   English

如何使用Protocol Buffers将多态对象数组序列化为文件?

[英]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? 谷歌的协议缓冲区是否适用于此目的,或者可能首选其他库?

Protocol Buffers allow for repeated fields these act like std::vector in your code. 协议缓冲区允许重复字段,这些字段在代码中就像std::vector As for polymorphic objects, you can use the extension framework. 对于多态对象,您可以使用扩展框架。 See here under the extension header. 请参阅扩展标题下的此处

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM