Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define a template function that only accepts a base class with parameter T of type its subclass?

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading