简体   繁体   中英

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?

BaseClass is a base class of hierarchy of classes, it has several sub classes. 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. 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 . 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:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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