Re: message processing using template
On Fri, 2012-05-18, red floyd wrote:
On 5/18/2012 6:00 AM, kira kira wrote:
Hi,
Suppose there are messages required to process. the code would look
like this.
void process (int type)
{
if (type == MSG_TYPE_A)
{
processMsgA();
}
else if (type == MSG_TYPE_B)
{
processMsgB();
}
}
I would like to know if it is possible to use template to achieve the
same result.
Use inheritance an virtual functions.
struct Message {
virtual void Process() = 0;
virtual ~Message() { }
};
struct MsgA : public Message {
....
struct MsgB : public Message {
....
I'm guessing (based on his other posting mentioning sequence numbers)
that the messages are part of some network protocol, perhaps an
UDP-based one like GTP or L2TP. Or perhaps he's implementing TCP ...
I find a less object-oriented approach the best. A dumb class
RxMessage for parsing messages I receive, and TxMessage for building
messages I need to send. These would know about the general message
format only -- typically a header with message type, sequence number,
checksum and so on, followed by type-specific data.
I may need to both read and write MSG_TYPE_FOO messages, but creating
a single MessageFoo class would be a mistake -- reading and writing
are two completely different things.
Also, I believe creating a fully parsing MessageFoo is often a
mistake. Some of these protocols have messages with a very rich inner
structure. There may be dozens of possible fields of various types.
Expressed as a C++ struct that can turn into dozens of vectors, most
of which are empty most of the time. A waste of resources -- and
almost as hard to interpret as the original binary message was!
The actual processing logic goes into other classes called things like
Retransmitter, Connection, Session, Peer ... depending on the protocol.
/Jorgen
--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]