Dek*_*ruk 11 c++ pointers stl const
我的问题通过以下示例说明:
#include <set>
class A {};
int main()
{
A a;
A * p = &a;
const A * cp = &a;
std::set<A*> s;
s.insert(p);
s.find(cp);
}
Run Code Online (Sandbox Code Playgroud)
编译以:
a.cpp: In function ‘int main()’:
a.cpp:13:18: error: invalid conversion from ‘const A*’ to ‘std::set<A*>::key_type {aka A*}’ [-fpermissive]
s.find(cp);
^
In file included from /usr/include/c++/4.9.1/set:61:0,
from a.cpp:1:
/usr/include/c++/4.9.1/bits/stl_set.h:701:7: note: initializing argument 1 of ‘std::set<_Key, _Compare, _Alloc>::iterator std::set<_Key, _Compare, _Alloc>::find(const key_type&) [with _Key = A*; _Compare = std::less<A*>; _Alloc = std::allocator<A*>; std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<A*>; std::set<_Key, _Compare, _Alloc>::key_type = A*]’
find(const key_type& __x)
Run Code Online (Sandbox Code Playgroud)
我知道为什么它不能编译,但有没有比丑陋和残酷更少的解决方案s.find((A*)cp)?给出了set和const指针.
T.C*_*.C. 10
std::set<A*, std::less<>> s;
s.find(cp);
Run Code Online (Sandbox Code Playgroud)
遗憾的是,libstdc ++当前不支持异构查找,但它标记为WIP.(这是在铛/可的libc ++和将可在Visual Studio的下一个版本).没有它,你几乎套牢const_cast"ING cp.