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

How to use ProtoBuf extensions to get polymorphism in C++

我正在尝试定义一个通用的基本消息,它定义了消息的类型(以便于解析),然后用实际消息进行扩展。消息将以 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;
    }
}

有点类似于this example,但我似乎无法通过

设置扩展值
Command commandRequest;
commandRequest.set_type(Command_Type_Request);

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

commandRequest.SetExtension(Request::command, extension);

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

error C2039: 'Set' : is not a member of 'google::protobuf::internal::MessageTypeTraits'

遗憾的是,这个similar question也没有提供c++下构造的例子。

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

我按照 documentation, which only sets basic types. I also tried to understand how rpcz 中 "nested extensions" 下的示例解决了这个问题,但我失败了,也许一些提示可以帮助解决这个问题?

扩展很像常规字段。对于原始字段,您可以使用访问器来获取和设置字段。但是,对于子消息,您不会获得 "set" 访问器——您会获得 "get" 和 "mutable",就像您对常规子消息字段所做的那样。所以,你想要:

Request* request =
    commandRequest.MutableExtension(Request::command);
request->set_guid("myGuid");