如何使用ProtoBuf扩展来获得C++中的多态性

x29*_*29a 3 c++ protocol-buffers zeromq

我试图定义一个公共基本消息,它定义消息的类型(为了更容易解析),然后用实际消息扩展.消息将以RPC方式使用.

我的.proto文件

syntax = "proto2";
package userapi;

// wrapper for commands
message Command
{
    // for "subclassing"
    extensions 100 to max;

    enum Type
    {
        Request = 1;
        Response = 2;
    }

    required Type type = 1;
}   

message Request
{
    // register this message type as extension to command
    extend Command
    {       
        optional Request command = 100;
    }

    optional string guid = 1;
}

message Response
{
    // register this message type as extension to command
    extend Command
    {       
        optional Response command = 101;
    }

    optional string guid = 1;

    //! error handling for command
    optional ErrorMsg error = 2;

    message ErrorMsg
    {
        enum ErrorCode
        {
            //! no error occured
            NONE = 0;
            //! the requested GUID already existed
            GUID_NOT_UNIQUE = 1;
        }

        optional string ErrorString = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

有点类似于这个例子,但我似乎无法通过设置扩展值

Command commandRequest;
commandRequest.set_type(Command_Type_Request);

auto extension = commandRequest.GetExtension(Request::command);
extension.set_guid("myGuid");

commandRequest.SetExtension(Request::command, extension);
Run Code Online (Sandbox Code Playgroud)

SetExtension()调用失败,并显示以下错误消息

错误C2039:'设置':不是'google :: protobuf :: internal :: MessageTypeTraits'的成员

不幸的是,这个类似的问题也没有以c ++为例构建一个例子.

我是否误解了扩展的概念?什么是更简洁的方法来建立这个(不,我不想将命令序列化为字符串).

我正在按照文档中 "嵌套扩展"下的示例进行操作,该文档仅设置基本类型.我也试图了解rpcz如何解决这个问题,但我失败了,也许一些提示会有助于解决这个问题?

Ken*_*rda 6

扩展很像常规字段.对于原始字段,您可以获取和设置字段的访问者.但是,对于子消息,您没有获得"设置"访问者 - 您获得"获取"和"可变",就像您对常规子消息字段一样.所以你要:

Request* request =
    commandRequest.MutableExtension(Request::command);
request->set_guid("myGuid");
Run Code Online (Sandbox Code Playgroud)