Protocol buffers 使用boost::mpl反序列化协议缓冲区

Protocol buffers 使用boost::mpl反序列化协议缓冲区,protocol-buffers,boost-mpl,Protocol Buffers,Boost Mpl,我使用PB-like: enum EMessages { E_MSG_METHOD_CONNECT = 0x8001, E_MSG_EVENT_CONNECT = 0xA001, ... } struct MsgHeader { required int32 sessionRef = 1; required int32 transactionId = 2; required int32 status = 3; } struct MSG_MET

我使用PB-like:

enum EMessages {
  E_MSG_METHOD_CONNECT = 0x8001,
  E_MSG_EVENT_CONNECT  = 0xA001,
 ...
}

struct MsgHeader {
  required int32  sessionRef    = 1;
  required int32  transactionId = 2;
  required int32  status        = 3;
}

struct MSG_METHOD_CONNECT {
  optional Messages    opCode  = 1 [default = E_MSG_METHOD_CONNECT];
  required MsgHeader   header  = 2;
  .. other fields ..
}
现在,我定义了一个接口和一个模板类来添加一个间接级别:

class IMessage {
  virtual INT     getOpCode() = 0;
  virtual STRING  getName() = 0;
  virtual size_t  getSize() = 0;
  virtual INT     SerializeToString(STRING& out) = 0;
  virtual INT     ParseFromString(STRING& in) = 0;
  ....
}

template<class MESSAGE>
class IMessageImpl : public IMessage {
  protected:
    MESSAGE   m_Message;  ///< The Message Implementation
  public:
    virtual MESSAGE&  getMessage() = 0;
};
class-IMessage{
虚拟INT getOpCode()=0;
虚拟字符串getName()=0;
虚拟大小\u t getSize()=0;
虚拟整型序列化字符串(字符串和输出)=0;
虚拟INT ParseFromString(STRING&in)=0;
....
}
模板
类IMessageImpl:公共IMessage{
受保护的:
MESSAGE m_MESSAGE;//<消息实现
公众:
虚拟消息&getMessage()=0;
};
我将把它用作:

IMessageImpl<MSG_METHOD_CONNECT> MsgConnect;
IMessageImpl-MsgConnect;
现在,当我从端点接收数据时,我当然需要根据消息操作码对其进行反序列化。
阅读本文时,我正在考虑使用boost::mpl::map之类的类型映射,但由于我从未使用过它,所以我正在寻找一些建议。

>

关于上面的代码,我尝试用以下方式进行编码:

template<class MESSAGE>
class PBMessage : public IMessageImpl<MESSAGE>
{
public:
  PBMessage() {};
  /* ... other methods ... */
};


// Map of types. The key is the Message opCode
typedef typename mpl::map< mpl::pair<mpl::int_[100], PBMessage<MSG_METHOD_CONNECT> >, 
                           mpl::pair<mpl::int_[101], PBMessage<MSG_EVENT_CONNECT> >,
                         > TMessageMap;

// The Message type
template < typename MessageMap, int opCode >
typedef typename mpl::at<MessageMap, mpl::int_<opCode> >::type::value  TMessage;
模板
PBMessage类:公共IMessageImpl
{
公众:
PBMessage(){};
/*…其他方法*/
};
//类型图。关键是消息操作码
typedef typename mpl::mapTMessageMap;
//消息类型
模板
typedef typename mpl::at::type::value TMessage;
为了从接收到的缓冲区创建消息,我尝试编写代码(将其作为伪代码):

PBMessageFactory类:公共IMessageFactory{ 公众: IMessage*createMessage(字符*buff,单位大小){ int操作码=buff[0]; TMessage-msg; msg.ParseFromString(STRING(buff)); } }; 但是没有成功…有人能给我一些建议如何从mpl::map检索类型吗?

谢谢,

Daniele.

我认为这一事件的“可怕性”被高估了。你需要读一篇博文来理解他的版本,而即使是一个刚开始的程序员也会理解这个大的
switch
语句。但也许有更好的方法来实现它?也许只是构建一个像:boost::mpl::map这样的映射?
  class PBMessageFactory : public IMessageFactory {
  public:
    IMessage* createMessage(CHAR* buff, UINT size) {
      int opCode = buff[0]; 
      TMessage<TMessageMap, opCode> msg;
      msg.ParseFromString( STRING(buff) );
    }        
  };