簡體   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