简体   繁体   English

无法将'const pointer const'传递给const ref

[英]Can't pass 'const pointer const' to const ref

Suppose you have a set of pointers (yeah...) : 假设你有一组指针(是的......):

std::set<SomeType*> myTypeContainer;

Then suppose that you want to search this set from a const method of SomeType: 然后假设您要从SomeType的const方法搜索此集合:

bool SomeType::IsContainered() const
{
    return myTypeContainer.find(this) != myTypeContainer.end();
}

This doesn't work. 这不起作用。 The this ptr in the method is a const SomeType *const , which I can't put into the find . 方法中的this ptr是一个const SomeType *const ,我无法将其放入find The issue being that find takes a const-ref, which in this case would mean that the passed pointer is treated as const, but not the thing it points to. 问题是find需要一个const-ref,在这种情况下,这意味着传递的指针被视为const,但不是它指向的东西。

Is there a way to resolve this smoothly (without changing the set template type)? 有没有办法顺利解决这个问题(不改变设置的模板类型)?

In order to enable "mixed" comparison in an ordered container, you can use a key_compare type that declares the typename key_compare::is_transparent . 为了在有序容器中启用“混合”比较,可以使用声明typename key_compare::is_transparentkey_compare类型。

The default comparison functor class of set is std::less<Key> . set的默认比较functor类是std::less<Key> It is not "transparent". 它不是“透明的”。 But std::less<void> is "transparent" and performs the comparison of any arguments a and b as long as a<b is well formed. 但是std::less<void>是“透明的”并且只要a<b形成良好,就执行任何参数ab的比较。 So you could define your own comparison functor type or you could use std::less<void> (or equivalently std::less<> ): 因此,您可以定义自己的比较函数类型,或者可以使用std::less<void> (或等效的std::less<> ):

set<SomeType*,std::less<>> myTypeContainer;

As you said, in the const member function this becomes const SomeType * (ie pointer to const), it can't be implicitly converted to SomeType * (ie pointer to non-const ), which is the expected parameter type of find . 正如你所说,在const成员函数中, this变成了const SomeType * (即指向const的指针),它不能被隐式转换为SomeType * (即指向非const的指针),这是find的预期参数类型。

You could use const_cast to perform explicit conversion. 您可以使用const_cast执行显式转换。

bool SomeType::IsContainered() const
{
    return myTypeContainer.find(const_cast<SomeType *>(this)) != myTypeContainer.end();
}

It would be safe if the cast result is not used for modifying; 如果铸造结果不用于修改,那将是安全的; while std::set::find won't do that. std::set::find不会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM