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?
Based on comments from experts in the question, I implemented the following generic function:
The client can simply write the following code and appropriate
fun()version will be called:Thank you all for the help.