调用 std::set<Type*>::find 时避免 const_cast

2022-01-17 00:00:00 set constants c++ 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.

相关文章