以下代码因标记的行无法使用,因为s.find
需要int*
,而不是const int*
。由于变量b
没有任何变化,为什么不能这样调用方法?有没有比const_cast
更好的方式?
#include <set>
int main()
{
int x = 5;
int* a = &x;
const int* b = a;
std::set<int*> s;
s.insert(a);
s.find(b); // does not work
s.find(const_cast<int*>(b)); // does work, but const_cast
}
错误是
error: no matching function for call to 'std::set<int*>::find(const int*&)'
之后它尝试隐式转换,并以
失败
error: invalid conversion from 'const int*' to 'std::set<int*>::key_type {aka int*}' [-fpermissive]