我很感激任何帮助,因为C++不是我的主要语言.
我有一个在多个库中派生的模板类.我试图找出一种方法来唯一地为每个派生类分配一个id int.我需要能够通过静态方法来实现,即.
template < class DERIVED >
class Foo
{
public:
static int s_id()
{
// return id unique for DERIVED
}
// ...
};
谢谢! 当实现MessageFactory类来实例化Message对象时,我使用了类似的东西:
class MessageFactory
{
public:
static Message *create(int type)
{
switch(type) {
case PING_MSG:
return new PingMessage();
case PONG_MSG:
return new PongMessage();
....
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常但每次添加新消息时我都要添加一个新的XXX_MSG并修改switch语句.
经过一些研究后,我发现了一种在编译时动态更新MessageFactory的方法,因此我可以添加任意数量的消息,而无需修改MessageFactory本身.这样可以更简洁,更容易维护代码,因为我不需要修改三个不同的位置来添加/删除消息类:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
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
{
enum { _MESSAGE_ID = TYPE }; …Run Code Online (Sandbox Code Playgroud)