【问题标题】:How to serialize an array of polymorphic objects to file using Protocol Buffers?如何使用协议缓冲区将多态对象数组序列化为文件?
【发布时间】:2014-11-05 18:30:59
【问题描述】:

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

BaseClass是类层次结构的基类,它有几个子类。 Google 的 Protocol Buffers 是否适合此目的,或者可能会首选其他库?

【问题讨论】:

    标签: c++ serialization protocol-buffers


    【解决方案1】:

    正如上面所说,你必须使用扩展机制来实现多态性。 这个链接你可能会觉得有用http://www.indelible.org/ink/protobuf-polymorphism/

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        您可以创建一个列表消息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,您还可以插入带有类型信息的枚举并添加相应的可选消息字段:

        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;
            ...
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-15
          • 2011-05-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多