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

标签 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
        }
    */
}

我需要从“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/

相关文章:

c++ - 在 raspbian 上构建时出现 gcc 编译器错误

c++ - 斐波那契和 'if constexpr'

c++ - 检查模板参数

java - 为什么要编译?

c++ - 将 QuickTime 音频复制到另一个 QuickTime 影片

c++ - 崩溃后 Dispatch Pointer 发生了什么

c++ - 构建后加载错误

javascript - 如何设置移动设备和桌面的宽度?

c++ - 确定编译器为给定的 C 风格转换生成什么

java - 从 double 转换为 int 而不截断为零