Is there any problem in performing dynamic casting via the following function?
template<typename Base, typename Derived>
requires std::is_convertible_v<Derived&, Base&> &&
std::is_polymorphic_v<Base>
inline std::unique_ptr<Derived> cast_to(std::unique_ptr<Base>&& ptr)
{
return std::unique_ptr<Derived>(dynamic_cast<Derived*>(ptr.release()));
}
Yes, your function can easily leak memory if the cast fails. Consider the following:
Demo
From this snippet you can also see another small issue: because of the order of the template parameters you have to supply them both. You can't let the compiler deduce
Basebecause it comes beforeDerived.With both of those issues in mind, the following would be a better implementation:
This fixes both of the above issues:
Demo