调用std :: set< Type *> :: find时避免const_cast [英] Avoiding const_cast when calling std::set<Type*>::find

查看:78
本文介绍了调用std :: set< Type *> :: find时避免const_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好的方法可以消除下面的 const_cast ,同时保持const的正确性?



没有 const_cast 下面的代码无法编译。 set :: find 获取对该集合的键类型的const引用,因此在我们这种情况下,它保证不更改传入的指针值;但是,不能保证不更改指针指向的内容。

  C类{
public:
std :: set< int *> m_set;

bool isPtrInSet(const int * ptr)const
{
return m_set.find(const_cast< int *>(ptr))!= m_set.end();
}
};


解决方案

。。 p>

在C ++ 14中,您可以使用自己的比较器将 int const * 声明为透明。这将使 find的模板超载 ()可以将键与任意类型进行比较。请参阅与此相关的 SO问题。这是乔纳森·韦克利的解释


Is there any good way to obviate the const_cast below, while keeping const correctness?

Without const_cast the code below doesn't compile. set::find gets a const reference to the set's key type, so in our case it guarantees not to change the passed-in pointer value; however, nothing it guaranteed about not changing what the pointer points to.

class C {
public:
   std::set<int*> m_set;

   bool isPtrInSet(const int* ptr) const
   {
       return m_set.find(const_cast<int*>(ptr)) != m_set.end();
   }
};

解决方案

Yes.

In C++14, you can use your own comparator that declares int const* as transparent. This would enable the template overload of find() that can compare keys against arbitrary types. See this related SO question. And here's Jonathan Wakely's explanation.

这篇关于调用std :: set&lt; Type *&gt; :: find时避免const_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆