user64141 user64141 - 2 months ago 10
C++ Question

Downcasting template typename object in C++

I have the following function in a C++ application that is called many different times:

template<typename The_ValueType>
void
handleObject(The_ValueType const &the_value) //unchangable function signature
{
/*
//Pseudo Java code (not sure how to implement in C++)
if (the_value instanceof Person){
Person person = (Person) the_value
//do something with person
}
if (the_value instanceof Integer){
int theInt = (Integer) the_value
//do something with int
}
*/
}


I need to print out some debugging information from the "the_value" object. Unfortunately, I'm from a Java/JavaScript background, and I'm horribly inefficient and unknowledable with C++. When I try to downcast in C++, I keep getting the error "invalid target type for dynamic_cast". How can implement the "Pseudo Java code" listed? Basically, I just need to know how to do the downcast, be the object a primitive or an object. I'm ripping my hair out trying to understand pointers and casting, and any guidance would be thoroughly appreciated.

Answer

There is nothing about downcasting here. You should use template specialization:

template<typename The_ValueType>
void
handleObject(const The_ValueType &the_value)
{ 
    // default implementation: do nothing or something else
}

template<>
void
handleObject<Person>(const Person &the_value)
{ 
    //do something with the_value as Person
}

template<>
void
handleObject<int>(const int &the_value)
{ 
    //do something with the_value as int
}

Or even better if all types are known, you can use overloading:

void handleObject(const Person &the_value)
{ 
    //do something with the_value as Person
}

void handleObject(const int &the_value)
{ 
    //do something with the_value as int
}
Comments