c++protobuf-c

Using "string_view" to represent the "string" key


When I use map<string, string> kv; in protobuf 3.8.0, the next code works:

std::string_view key("key");
kv[key] = "value";

While in protobuf 3.19.4, the above code doesn't work.

The error msg is:

error: no match for 'operator[]' (operand types are 'google::protobuf::Map<std::__cxx11::basic_string , std::__cxx11::basic_string>' and 'std::string_view' {aka 'std::basic_string_view'})


Solution

  • In 3.8.0, Map::operator[] is declared as:

    Value& operator[](const Key& k)
    

    Where, in your case, Key is std::string. std::string_view is convertible to std::string, which is why the code works in 3.8.0.

    In 3.19.4, Map::operator[] is declared as:

    template <typename K = key_type>
    T& operator[](const key_arg<K>& key)
    
    template <
        typename K = key_type,
        // Disable for integral types to reduce code bloat.
        typename = typename std::enable_if<!std::is_integral<K>::value>::type>
    T& operator[](key_arg<K>&& key)
    

    Where key_arg is declared as:

    template <typename LookupKey>
    using key_arg = typename internal::TransparentSupport<key_type>::template key_arg<LookupKey>;
    

    And, in your case, key_type is std::string. std::string_view is not convertible to TransparentSupport::key_arg, which is why the code doesn't work in 3.19.4.