添加到 Protocol Buffers 重复字段

Adding to a Protocol Buffers repeated field

我正在使用 C++ 使用 Protocol Buffer 模板,其中包括以下消息:

message StringTable {
   repeated bytes s = 1;
}

我正在尝试向现有数据添加新值,如下所示:

pb.stringtable().s().Add(replace_key);

但是,这会在编译时产生错误(在 OS X 上使用 clang):

test.cpp:51:4: error: member function 'Add' not viable: 'this' argument 
  has type 'const ::google::protobuf::RepeatedPtrField< ::std::string>', 
  but function is not marked const
                    pb.stringtable().s().Add(replace_key);
                    ^~~~~~~~~~~~~~~~~~~~

有线索吗?我是一个 C++ 新手,所以可能会犯一个愚蠢的错误。


编辑:

使用访问器会产生类似的错误:

pb.stringtable().add_s(replace_key);

结果:

test.cpp:51:21: error: no matching member function for call to 'add_s'
                        pb.stringtable().add_s(replace_key);
                        ~~~~~~~~~~~~~~~~~^~~~~
./osmformat.pb.h:3046:26: note: candidate function not viable: 'this' argument has type 'const ::StringTable', but method is not marked const
inline void StringTable::add_s(const ::std::string& value) {
                     ^
./osmformat.pb.h:3050:26: note: candidate function not viable: 'this' argument has type 'const ::StringTable', but method is not marked const
inline void StringTable::add_s(const char* value) {
                     ^
./osmformat.pb.h:3043:36: note: candidate function not viable: requires 0 arguments, but 1 was provided
inline ::std::string* StringTable::add_s() {
                               ^
./osmformat.pb.h:3054:26: note: candidate function not viable: requires 2 arguments, but 1 was provided
inline void StringTable::add_s(const void* value, size_t size) {

问题已解决。

默认情况下,现有的 StringTable 是不可变的。但是,使用 mutable_ 访问器可以做到这一点:

pb.mutable_stringtable().add_s(replace_key);