use*_*141 1 c++ templates casting
我在C++应用程序中有以下函数,它被称为许多不同的时间:
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
}
*/
}
Run Code Online (Sandbox Code Playgroud)
我需要从"the_value"对象打印出一些调试信息.不幸的是,我来自Java/JavaScript背景,而且我非常低效且无法使用C++.当我尝试在C++中向下转换时,我不断收到错误"dynamic_cast的无效目标类型".如何实现列出的"伪Java代码"?基本上,我只需要知道如何进行向下转换,作为原始对象或对象.我正试图理解指针和铸造,试图撕掉我的头发,任何指导都会被彻底欣赏.
这里没有任何关于向下倾倒的事情.你应该使用模板专业化:
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
}
Run Code Online (Sandbox Code Playgroud)
或者甚至更好,如果所有类型都已知,您可以使用重载:
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
}
Run Code Online (Sandbox Code Playgroud)