繁体   English   中英

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

[英]How to serialize an array of polymorphic objects to file using Protocol Buffers?

有一个数组std::vector<BaseClass*>使用Google的Protocol Buffers库将这个数组保存到文件的正确方法是什么?

BaseClass是类的层次结构的基类,它有几个子类。 谷歌的协议缓冲区是否适用于此目的,或者可能首选其他库?

协议缓冲区允许重复字段,这些字段在代码中就像std::vector 对于多态对象,您可以使用扩展框架。 请参阅扩展标题下的此处

您可以创建一个列表消息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;
    ...
}

如上所述,您必须使用扩展机制来实现多态。 您可以找到有用的链接http://www.indelible.org/ink/protobuf-polymorphism/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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