添加到协议缓冲区重复字段

时间:2015-01-02 13:34:30

标签: c++ protocol-buffers

我使用协议缓冲区模板在C ++中工作,包括以下消息:

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) {

1 个答案:

答案 0 :(得分:2)

问题解决了。

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

pb.mutable_stringtable().add_s(replace_key);