I have a Message class that is able to pack its payload to binary and unpack it back. Like:
PayloadA p;
msg->Unpack(&p);
where PayloadA is a class.
The problem is that I have a bunch of payloads, so I need giant if or switch statement:
if (msg->PayloadType() == kPayloadTypeA)
{
PayloadA p;
msg->Unpack(&p); // void Unpack(IPayload *);
// do something with payload ...
}
else if ...
I want to write a helper function that unpacks payloads. But what would be the type of this function? Something like:
PayloadType UnpackPayload(IMessage *msg) { ... }
where PayloadType is a typedef of a proper payload class. I know it is impossible but I looking for solutions like this. Any ideas?
Thanks.
I would split one level higher to avoid the problem entirely:
To further reduce the code size, try to make
Unpacka function template (possible easily only if it’s not virtual, if it is you can try to add one level of indirection so that it isn’t ;):EDIT
Now let’s see how we can avoid writing the long list of
_actions[kPayloadN]. This is highly non trivial.First you need a helper to run code during the static initialization (i.e. before main):
Now we need to define our actual registration logic:
Then we factor in the parsing code:
Then we define all the payloads one by one
Finally we parse the incoming messages: