gpt4 book ai didi

c++ - 在 C++ 中向下转换模板类型名称对象

转载 作者:行者123 更新时间:2023-11-30 01:10:13 25 4
gpt4 key购买 nike

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

如果所有类型都已知,甚至更好,您可以使用重载:

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++ - 在 C++ 中向下转换模板类型名称对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38640245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com