在C ++中下转换模板类型名对象 [英] Downcasting template typename object in C++
问题描述
我在一个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
}
*/
}
我需要从the_value对象打印出一些调试信息。不幸的是,我来自Java / JavaScript背景,我非常低效和不可知的C ++。当我尝试在C ++中向下转换,我不断收到错误dynamic_cast的无效目标类型。如何实现伪Java代码列出?基本上,我只需要知道如何做downcast,对象是一个原始或对象。我撕开我的头发,试图理解指针和铸造,任何指导都会完全赞赏。
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.
推荐答案
这里没有关于downcasting的内容。您应该使用模板专业化:
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
}
这篇关于在C ++中下转换模板类型名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!