[英]Why can't map::find a pointer to a const?
簡單地說,為什么不編譯
#include <map>
int main()
{
std::map<int*, char> m;
const int *x = nullptr;
m.find(x);
}
那不是有效的代碼可能是什么原因?
為什么要find
它是指向const的指針還是指向const的指針呢?
看起來和聞起來像個蟲子...
不用了,不用const_cast
看起來和聞起來像個蟲子...
為什么會是錯誤?
find
的參數是對鍵類型的const引用(對int *
const引用)。
您不能將const int *
綁定到這樣的引用,因為const int *
不能隱式轉換為int *
。
從C ++ 14開始,您可以使用透明的比較器來解決此問題: std::map<int*, char, std::less<>>
。
使用透明的comaprator, find
將成為模板。 只要可以與鍵類型進行比較,它將適用於任何參數類型。
std::map<int*, char>
的默認版本使用less<int*>
作為比較器,該比較器又在其中定義了函數()(const int*, const int*)
。
此函數將不接受int*
但是,如果使用less<>
,它將起作用:
std::map<int*, char, std::less<>> m;
原因是std::less<void>
定義了模板函數,
template< class T, class U>
constexpr auto operator()( T&& lhs, U&& rhs ) const
當比較const和非const指針時,這很好用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.