C++中的下播模板typename对象
Downcasting template typename object in C++
我在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
}
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 在C++中,我想通过使用来自变量(例如字符串)的typename信息,从模板中定义一个类对象
- 如何初始化Typename为T的类对象
- C++中的下播模板typename对象