briefly, why does it not compile
#include <map>
int main()
{
std::map<int*, char> m;
const int *x = nullptr;
m.find(x);
}
What could possibly be the reason for that not to be a valid piece of code?
Why does it matter to find
whether it's a pointer or a pointer to a const??
Looks and smells like a bug...
And no thanks, no const_cast
Looks and smells like a bug...
Why would it be a bug?
The parameter of find
is a const reference to the key type (const reference to int *
).
You can't bind const int *
to such a reference, since const int *
can't be implicitly converted to int *
.
Since C++14 you could fix that by using a transparent comparator: std::map<int*, char, std::less<>>
.
With a transparent comaprator find
becomes a template. It will work with any parameter type, as long as it can be compared with the key type.
The default version of std::map<int*, char>
uses less<int*>
as comparator, which, in turn, has function ()(const int*, const int*)
defined in it.
This function will not accept int*
However, if you use less<>
, it will work:
std::map<int*, char, std::less<>> m;
The reason for that is that std::less<void>
defines a template function,
template< class T, class U>
constexpr auto operator()( T&& lhs, U&& rhs ) const
And this works just fine when compares const vs non-const pointers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.