C++中的下播模板typename对象

Downcasting template typename object in C++

本文关键字:typename 对象 C++      更新时间:2023-10-16

我在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
        }
    */
}

我需要从"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
}

或者更好的是,如果所有类型都是已知的,您可以使用重载:

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
}