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
I believe that the problem has to do with the mismatch on the
key_type
. On one hand you have a multimap wherekey_type=int*
while on the other hand you are passing akey_type=const int*
thus attempting to drop the const qualifier on thekey_type
. I was confused by this too because I was expanding thekey_type
in my mind to getconst int*&
which should be compatible. However, the mismatch happens earlier on thekey_type
itself. At least that's the only logical explanation I could think of.My suggestion would be to make the
key_type
const int*
and keep your function parameter as is. After all, why would you need a pointer to a mutable value as a key to a map ?