一直在寻找c++的自动序列化库,希望能够自动生成序列化代码,像ICE、gSoap都有实现。gSoap主要是它只能序列化成基于xml的soap格式数据;而ICE好是好,可惜吃不起。最近有朋友推荐Protocol Buffer,这个东西基本上附合我的要求,可以序列化成高效的二进制格式,如果能够提供序列化成文本(如:XML)的功能,会便于调试。
手册上有一段话初看让人疑惑:
Protocol Buffers and O-O Design Protocol buffer classes are basically dumb data holders (like structs in C++); they don't make good first class citizens in an object model. If you want to add richer behaviour to a generated class, the best way to do this is to wrap the generated protocol buffer class in an application-specific class. Wrapping protocol buffers is also a good idea if you don't have control over the design of the .proto file (if, say, you're reusing one from another project). In that case, you can use the wrapper class to craft an interface better suited to the unique environment of your application: hiding some data and methods, exposing convenience functions, etc. You should never add behaviour to the generated classes by inheriting from them. This will break internal mechanisms and is not good object-oriented practice anyway.
大意是不要从它生成的Message类进行派生,以便加入一些行为函数,而应该采用包装(wrap)的方式,说白了就是组合(在你的类中放一个生成的Message类成员变量)。通过查看邮件列表,载录以下详细解释:
 *如果进行派生,那么你的类中会混入Protocol Buffer生成的一些方法,而这些方法将来还可能会变化,
 这就意味着你的类将依赖Protocol Buffer的实现。用设计相关的术语就是:你继承了实现,你把业务和数据混在了一起。