Find a shared_ptr in an unordered_set with only a const shared_ptr?
Asked Answered
I

1

8

I have an unordered_set<shared_ptr<T>> us and I would like to know whether a needle k is in us, but k has type shared_ptr<T const> so unordered_set<shared_ptr<T>>::find complains that it cannot convert.

Is there a way around this? Maybe by directly supplying the hash?

I did try const_cast (and felt dirty) but that didn't cut it.

Irresistible answered 8/6, 2018 at 10:16 Comment(2)
Not sure about this .... can shared_ptr<T> and shared_ptr<T const> own the same object, won't you have 2 owner blocks for the different object types?Harijan
@RichardCritten There's an implicit conversion from shared_ptr<T> to shared_ptr<T const> that does the right thing. But also, you can even have shared_ptr<T> and shared_ptr<int> share ownership, using the aliasing constructors. (That might be used to produce a shared pointer to a member of a class which is owned by a shared pointer. When the last pointer sharing ownership is destroyed, the original deleter is called, ignoring the type of the last shared pointer.)Thrifty
T
10

Using std::const_pointer_cast is a possible solution here.

us.find(std::const_pointer_cast<T>(k));

Since you're not modifying k, it's okay to cast away the const.

Tiedeman answered 8/6, 2018 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.