I have an accessor function that returns a const reference to a type (std::map) … …
myMap_t const& getMap() const {return paramMap;}
The type has an overloaded [] operator. What is the syntax to then use the [] operator directly from the getter function in a way like the following, but that actually works.
parameter = contextObj.getMap()[key];
Error message is:
context.cpp:35: error: passing
'const std::map<
std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
float,
std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,
std::allocator<std::pair<
const std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
float> > >'
as 'this' argument of
'_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
with
_Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
_Tp = float,
_Compare = std::less<std::basic_string<char, std::char_traits<char>, td::allocator<char> > >,
_Alloc = std::allocator<std::pair<
const std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
float> >]'
discards qualifiers
The problem is that
operator[]in a map is a mutating operation, and you cannot call it on a const reference to a map. The reason that it is mutating is that it must return a reference to a value, and for that, if the key was not already present in the container, it will insert a new default constructed value addressed by that key and return the reference to it.If you have a const reference, and you want to determine whether an element is present (or access it), you must use
std::map<>::findthat will return an iterator. If the element is not present the value of the iterator would bem.end()