【发布时间】:2018-08-09 07:47:09
【问题描述】:
假设你有一组指针(是的......):
std::set<SomeType*> myTypeContainer;
然后假设你想从 SomeType 的 const 方法中搜索这个集合:
bool SomeType::IsContainered() const
{
return myTypeContainer.find(this) != myTypeContainer.end();
}
这不起作用。方法中的this ptr 是const SomeType *const,我无法放入find。问题在于 find 采用 const-ref,在这种情况下,这意味着传递的指针被视为 const,而不是它指向的东西。
有没有办法顺利解决这个问题(不改变设置的模板类型)?
【问题讨论】:
-
升级到 C++14:en.cppreference.com/w/cpp/container/set/find(见 3 或 4)
-
@Caleth ... 并相应地更改
Compare类型,例如std::set<SomeType *, std::less<>>.
标签: c++ templates pointers constants pass-by-const-reference