I have the following program. What I would like to accomplish is to create a constant reference to a mutable wrapper over unordered_map that I can pass around for read-only lookup. However, I am not able to compile the following code, due to the operator[] overloads.
From this code, does anyone know what I am doing wrong?
#include <unordered_map>
#include <string>
using std::unordered_map;
using std::string;
class M {
private:
unordered_map<string, string> m;
public:
string const& operator[](string const& s) const {
return m[s]; // line 13
}
string& operator[](string const& s) {
return m[s];
}
};
int main() {
M m;
m[string("a")] = string("answer_a");
M const& m1 = m;
string const& test = m1[string("a")];
return 0;
}
The error (on line 13) is
error: passing 'const std::unordered_map, std::basic_string >' as 'this' argument of 'std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::mapped_type& std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::operator[](const _Key&) [with _Key = std::basic_string, _Pair = std::pair, std::basic_string >, _Hashtable = std::_Hashtable, std::pair, std::basic_string >, std::allocator, std::basic_string > >, std::_Select1st, std::basic_string > >, std::equal_to >, std::hash >, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, false, false, true>, std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::mapped_type = std::basic_string]' discards qualifiers [-fpermissive]