Reputation: 207
I have the following piece of code -
#include <map>
using Type1 = std::map<std::string, unsigned long long>;
using Type2 = std::map<std::string, Type1>;
class T
{
private:
Type2 mymap;
public:
const Type1& get(const std::string& key) const;
};
const Type1& T::get(const std::string& key) const
{
return mymap[key];
}
int main(void)
{
}
This does not compile and the compiler complains -
maps.cpp: In member function ‘const Type1& T::get(const string&) const’: maps.cpp:17:20: error: passing ‘const Type2 {aka const std::map<std::basic_string<char>, std::map<std::basic_string<char>, long long unsigned int> >}’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::basic_string<char>; _Tp = std::map<std::basic_string<char>, long long unsigned int>; _Compare = std::less<std::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::basic_string<char>, std::map<std::basic_string<char>, long long unsigned int> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::map<std::basic_string<char>, long long unsigned int>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::basic_string<char>]’ discards qualifiers [-fpermissive] return mymap[key]; ^
I need help understanding this error. From what I can tell I am not modifying "this" in the get function.
Thanks!
Upvotes: 0
Views: 58
Reputation: 47794
The errors comes from the fact that
std::map::operator[]
can
inserts the key if the it does not exist.
You could do a std::map::find
first as a check.
Upvotes: 2