You can access the messages reflectively and static_cast them to the
concrete type. Just make sure you're casting to the correct type since
otherwise it will be undefined behavior. Something like this should work:

switch ((*msgItr)->number()) {
  case IncomingMessage::kCmsgFieldNumber:
    onMsg(static_cast<ControlMessage>(reflection->GetMessage(msg,
*msgItr)));
  case IncomingMessage::kAmsgFieldNumber:
    ...
}

On Fri, Nov 29, 2019 at 12:32 AM Iranjeet Singh <[email protected]>
wrote:

> I am trying to get the type of a data member inside a protobuf message and
> call the appropriate message from it.
>
> message ControlMessage{}
> message AdminMessage{}
> message ExecMessage{}
>
> message IncomingMessage{
>   optional ControlMessage cmsg = 1 ;
>   optional AdminMessage amsg   = 2 ;
>   optional ExecMessage  emsg   = 3 ;}
>
> void onMsg(const ControlMessage&){}void onMsg(const AdminMessage&){}void 
> onMsg(const ExecMessage&){}
> int main(){
>   IncomingMessage msg ;
>   msg.mutable_cmsg() ;
>   msg.mutable_emsg() ;
>
>   auto metadata = msg.GetMetaData() ;
>   auto reflection = metadata.reflection ;
>   auto descriptor = metadata.descriptor ;
>
>   std::vector<const FieldDescriptor*> all_fields ;
>
>   reflection->ListFields( msg, &all_fields ) ;
>
>   for(auto msgItr : all_fields)
>   {
>      // Somehow call the onMsg() overloads
>      // for all the fields set inside the msg
>      // msgItr is the FieldDescriptor
>   }
> }
>
> --
> You received this message because you are subscribed to the Google Groups
> "Protocol Buffers" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/protobuf/fc826c44-e139-4987-8dab-c7da3dc4858d%40googlegroups.com
> <https://groups.google.com/d/msgid/protobuf/fc826c44-e139-4987-8dab-c7da3dc4858d%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/protobuf/CADqAXr4GVTe5ZPO_CS%3DRhSk043g_dPqR_r7L6pdf8KVtB1UJqQ%40mail.gmail.com.

Reply via email to