It is not specific to casting. My scenario is how to define a template function that only accepts a base class for parameter T of type subclass.
template<typename T> // T must be a subclass
T* DoSomething(<I don't know> parent) // parent must be a base class
{
// here the specified subclass of type T is produced.
// return object of type T which is a subclass.
}
A contrived usage:
Parent* p = new Child();
Child* c = DoSomething<Child>(p);
delete p;
>Solution :
One way could be by using std::is_base_of or std::is_base_of_v in combination with a static_assert:
template<typename Derived, typename Base>
Derived* CastChecked(Base* parent)
{
static_assert(std::is_base_of_v<Base,Derived>);
return dynamic_cast<Derived*>(parent);
}