一直在尋找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的實現。用設計相關的術語就是:你繼承了實現,你把業務和數據混在了一起。