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

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

问题描述

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

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

如果没有 const_cast,下面的代码将无法编译.set::find 获取对集合键类型的 const 引用,因此在我们的例子中,它保证不会更改传入的指针值;但是,它不能保证不改变指针指向的内容.

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();
   }
};

推荐答案

.

在 C++14 中,您可以使用自己的比较器,将 int const* 声明为 transparent.这将启用 find()<的 模板重载/code> 可以将键与任意类型进行比较.请参阅此相关 SO 问题.这是 Jonathan Wakely 的解释.

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天全站免登陆