Dania Dania - 6 months ago 79
C++ Question

c++ protobuf: how to iterate through fields of message?

I'm new to protobuf and I'm stuck with simple task: I need to iterate through fields of message and check it's type. If type is message I will do same recursively for this message.

For example, I have such messages:

package MyTool;

message Configuration {
required GloablSettings globalSettings = 1;
optional string option1 = 2;
optional int32 option2 = 3;
optional bool option3 = 4;


message GloablSettings {
required bool option1 = 1;
required bool option2 = 2;
required bool option3 = 3;

Now, to explicitly access a field value in C++ I can do this:

MyTool::Configuration config;
fstream input("config", ios::in | ios::binary);

bool option1val = config.globalSettings().option1();
bool option2val = config.globalSettings().option2();

and so on. This approach is not convenient in case when have big amount of fields.

Can I do this with iteration and get field's name and type? I know there are descriptors of type and somewhat called reflection, but I didn't have success in my attempts.
Can some one give me example of code if it's possible?



Take a look at how the Protobuf library implements the TextFormat::Printer class, which uses descriptors and reflection to iterate over fields and convert them to text: