Here is this simple code
#include <map>
class MyMap : public std::multimap<int*, int*>
{
public:
void foo(const int* bar) const
{
equal_range(bar);
}
};
int main()
{
MyMap myMap;
int number;
myMap.foo(&number);
return 0;
}
It doesn't compile, and give the following error
error C2663: 'std::_Tree<_Traits>::equal_range' : 2 overloads have no legal conversion for 'this' pointer
I have seen many topic about this error, and it seems that it is a const issue. It compiles fine if I turn foo(const int* bar) into foo(int* bar).
Problem is, I don't see how foo content is supposed to change anything to my MyMap object. std::multimap proposes a const version of equal_range:
http://www.cplusplus.com/reference/map/multimap/equal_range/
What is my problem?
Thank you
Check the definition of equal_range:
It expects a constant reference to
key_type:const key_type& k.What you were trying to supply was a pointer to a constant integer:
const int* barWhy doesn't this work even though both values are
const?const int& foomeans that you cannot letfoorefer to another integer, but it is allowed to change the value of the referenced integer.const int* foomeans that you can letfoopoint to another integer, but you cannot change the value of the integer it points to.What the map actually expects is a
const int*& k, but the map will automatically convert this if you supply aint*only (without theconst).[Edit]
Also note that a
MyMapobject still cannot be changed by yourfoofunction even if you changeconst int*toint*as there still is another const at the end of yourfoofunction. This const at the very end declares the function as constant meaning that it cannot modify the current object in which it is executed. If it was trying to modify it or call anything that could potentially modify it, you would get a compiler error. (Disclaimer: There are ways to modify a class from within a const function anyway but that's another topic.)