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
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01