[英]Why can't map::find a pointer to a const?
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?? 为什么要find
它是指向const的指针还是指向const的指针呢?
Looks and smells like a bug... 看起来和闻起来像个虫子...
And no thanks, no const_cast
不用了,不用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 *
). find
的参数是对键类型的const引用(对int *
const引用)。
You can't bind const int *
to such a reference, since const int *
can't be implicitly converted to int *
. 您不能将const int *
绑定到这样的引用,因为const int *
不能隐式转换为int *
。
Since C++14 you could fix that by using a transparent comparator: std::map<int*, char, std::less<>>
. 从C ++ 14开始,您可以使用透明的比较器来解决此问题: std::map<int*, char, std::less<>>
。
With a transparent comaprator find
becomes a template. 使用透明的comaprator, find
将成为模板。 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. std::map<int*, char>
的默认版本使用less<int*>
作为比较器,该比较器又在其中定义了函数()(const int*, const int*)
。
This function will not accept int*
此函数将不接受int*
However, if you use less<>
, it will work: 但是,如果使用less<>
,它将起作用:
std::map<int*, char, std::less<>> m;
The reason for that is that std::less<void>
defines a template function, 原因是std::less<void>
定义了模板函数,
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. 当比较const和非const指针时,这很好用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.