Last active
January 31, 2016 05:15
-
-
Save dnmiller/5a1cb79827cf581870e9 to your computer and use it in GitHub Desktop.
Dynamic registration of message types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <inttypes.h> | |
// Taken from http://stackoverflow.com/questions/2850213 | |
class Message { | |
protected: | |
inline Message() {}; | |
public: | |
inline virtual ~Message() { } | |
inline int getMessageType() const { return m_type; } | |
virtual void say() = 0; | |
protected: | |
uint16_t m_type; | |
}; | |
template<int TYPE, typename IMPL> | |
class MessageTmpl: public Message | |
{ | |
private: | |
enum { _MESSAGE_ID = TYPE }; | |
public: | |
static Message* Create() { return new IMPL(); } | |
static const uint16_t MESSAGE_ID; // for registration | |
protected: | |
MessageTmpl() { m_type = MESSAGE_ID; } //use parameter to instanciate template | |
}; | |
typedef Message* (*t_pfFactory)(); | |
class MessageFactory | |
{ | |
public: | |
static uint16_t Register(uint16_t msgid, t_pfFactory factoryMethod) { | |
printf("Registering constructor for msg id %d\n", msgid); | |
m_List[msgid] = factoryMethod; | |
return msgid; | |
} | |
static Message *Create(uint16_t msgid) { | |
return m_List[msgid](); | |
} | |
static t_pfFactory m_List[65536]; | |
}; | |
template <int TYPE, typename IMPL> | |
const uint16_t MessageTmpl<TYPE, IMPL >::MESSAGE_ID = MessageFactory::Register( | |
MessageTmpl<TYPE, IMPL >::_MESSAGE_ID, &MessageTmpl<TYPE, IMPL >::Create); | |
class PingMessage: public MessageTmpl < 10, PingMessage > | |
{ | |
public: | |
PingMessage() {} | |
virtual void say() { printf("Ping\n"); } | |
}; | |
class PongMessage: public MessageTmpl < 11, PongMessage > | |
{ | |
public: | |
PongMessage() {} | |
virtual void say() { printf("Pong\n"); } | |
}; | |
t_pfFactory MessageFactory::m_List[65536]; | |
int main() { | |
Message *msg1; | |
Message *msg2; | |
msg1 = MessageFactory::Create(10); | |
msg1->say(); | |
msg2 = MessageFactory::Create(11); | |
msg2->say(); | |
delete msg1; | |
delete msg2; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment