This question already has an answer here:
What is the appropriate way to downcast a std::unique_ptr
? There's these other question that asks the same but I am unsure if it is under the OP's specific context or if that applies to the general case.
In that question, this is the solution:
template<typename Derived, typename Base, typename Del>
std::unique_ptr<Derived, Del>
static_unique_ptr_cast( std::unique_ptr<Base, Del>&& p )
{
auto d = static_cast<Derived *>(p.release());
return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter()));
}
But I've also seen only:
template<typename D, typename B>
std::unique_ptr<D> static_unique_ptr_cast(std::unique_ptr<B>& base)
{
return std::unique_ptr<D>(static_cast<D*>(base.release()));
}
Is there a good way to do this?
Do we need to move the deleter in general?
What happens if we do:
std::unique_ptr ptr = MakeDerived();
static_unique_ptr_cast(ptr)->DoSomething();
And why doesn't the standard provide this capability?
Aucun commentaire:
Enregistrer un commentaire