Avoiding const_cast when calling std::setlt;Type*gt;::find(调用 std::setlt;Type*gt;::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<Type*>::find 时避免 const_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调用 std::set<Type*>::find 时避免 const_cast
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
