Extending Protobuf with my own methods

How do I add Protobuf message methods?

Suppose I have a .proto file:

package proto; message Person { required string name = 1; required int32 id = 2; optional string email = 3; } 

and I want to add in the message, for example, the string concatenateNameEmail() .

Now I am creating my own C ++ class:

 class Person : public proto::Person { public: Person( proto::Person const & person_ ) : proto::Person(person_) {} string concateNateNameEmail() { ... } }; 

So, the disadvantage is that I need to call proto :: Person copy constructor. Is there a more elegant solution than this?

+6
c ++ protocol-buffers
source share
1 answer

Google Protobufs are not specifically designed for expansion. Here's a paragraph from the documentation (in the middle of this: http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html ):

Protocol Buffers and OO Design Protocol buffer classes are mostly dumb data owners (for example, structures in C ++); they do not make a good first class citizen in the object model. if you want to add richer behavior to the generated class, the best way to do this is to complete the created buffer class protocol in the application class .... You should never add behavior to the generated classes, inheriting from them. . This violates the internal mechanisms and is not a good object-oriented practice.

I see how such advice would seem annoying if you want only one method, but overall this is pretty good advice. Unless you have other functions that guarantee the creation of an application-specific Person class, there is nothing wrong with just defining a top-level function:

 string concatenateNameEmail(const proto::Person &person) { ... } 
+10
source share

All Articles