Generic function for dynamic casting base class to child class

89 Views Asked by At

I am working on a C++ project and I have a base class A which can have many derived classes like B, C, and so on.

I want to write a generic function for dynamic base class to whatever child class if possible. So I wrote the following function:

template<typename T>
optional<T> A::get_if_convertible()
{
    optional<T> return_val = none;
    using converted_ptr_type = typename std::add_pointer<T>::type;
    auto ptr = dynamic_cast<converted_ptr_type>(this);
    if (ptr)
        return_val = dynamic_cast<T>(ptr);
    return return_val;
}

What I need is if this is a pointer to a const object then my returned derived class object should also be const. Is this the correct way for dynamic casting? How to handle the case if this is a pointer to a const object?

1

There are 1 best solutions below

0
Vivek Mangal On

Based on comments from experts in the question, I implemented the following generic function:

template <typename T>
T* A::get_if_convertible() {
    return dynamic_cast<T*>(this);
}

template <typename T>
const T* A::get_if_convertible() const {
    return dynamic_cast<const T*>(this);
}

The client can simply write the following code and appropriate fun() version will be called:

void fun(const B* b);
    
void fun(B* b);

int main()
{
    auto ptr_A = get_A_ptr();
    fun(ptr_A->get_if_convertible<B>());
}

Thank you all for the help.