I am attempting to use the new protobuf Map functionality in C++.
The following was done on Ubuntu 14.04 with gcc 4.9.2 C++14 and protobuf 3.0.0-alpha-4:
Message definition:
message TestMap {
map<string,uint64> map1 = 1;
}
Then, I tried to compile the following example program:
auto test = debug::TestMap::default_instance();
auto map = test.mutable_map1();
string key = "key";
uint64 val = 20;
map[key] = val;
Acccessing the map using the [] syntax works totally fine for std::unordered_map. But the protobuf implementation always yields the following compiler error:
error: no match for ‘operator[]’ (operand types are ‘google::protobuf::Map<std::basic_string<char>, long unsigned int>*’ and ‘std::string {aka std::basic_string<char>}’)
I do not understand why this operator is not known, because the header file google::protobuf::Map is clearly found and this should be an elementary operation.
Do you have any idea what goes wrong here? I would welcome any example of using the new protobuf maps, as I haven't found any online after researching for hours.
According to Google protobuf doc, proto 2 does support map type https://developers.google.com/protocol-buffers/docs/proto#maps . As I quote, Maps cannot be repeated, optional, or required.
This is protobuf-c, a C implementation of the Google Protocol Buffers data serialization format. It includes libprotobuf-c , a pure C library that implements protobuf encoding and decoding, and protoc-c , a code generator that converts Protocol Buffer . proto files to C descriptor code.
proto3 is the current version of the language. This is the most commonly used version of the language. We encourage new code to use proto3. proto2 is an older version of the language.
As Pixelchemist pointed out, the problem is that map
is a pointer so the []
operator does not work.
Thus, the pointer needs to be dereferenced first. *map[key]
also does not work, as the compiler first parses []
and then the *
. The following does work:
(*map)[key] = val;
Although this is a quite basic problem, this represents a good learning opportunity for C++ and Protocol Buffers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With