c++ - How to provide const read-only access to a wrapper class -
i have following program. accomplish create constant reference mutable wrapper on unordered_map can pass around read-only lookup. however, not able compile following code, due operator[] overloads.
from code, know 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 >' '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]
the unordered_map operator[] non-const, because adds map key when not exist yet. instead, should use
return m.at(s);