c++ 我需要在结构中存储具有继承和虚函数的各种类之间的对象"type"

c++ I need to store in a structure the "type" of an object among various classes with inheritance and virtual functions

本文关键字:函数 之间 type 对象 种类 继承 结构 存储 c++      更新时间:2023-10-16

我用g++。

我有一个继承前一个类的类层次结构。

相同的类有两个版本,一个版本是Plain Old Data POD简单结构体,另一个版本包含虚函数。

我已经看到了typeid,所以我用POD结构保存了它。

我现在需要使用保存的类型id转换POD数据并拥有多态类。

我该怎么做呢?

示例代码如下:

#include <iostream>    // cout
#include <typeinfo>  //for 'typeid'
struct Person0{
    int weight;
};
struct Employee0:Person0{
    double salary;
};
struct Person: Person0 {
public:
   // ... Person members ...
   virtual ~Person() {}
};
struct Employee:Employee0,Person {
   // ... Employee members ...
};
int main() 
{
   Person person;
   Employee employee;
     void *p1=&person;      const std::type_info* p1t=&typeid(person);
     void *p2=&employee;    const std::type_info* p2t=&typeid(employee);
// now I need to get back to person using only p1 and p1t 
// and to employee 
     Person personCopy = *some_casting<*p1t>(p1);
     Employee employeeCopy = *some_casting<*p2t>(p2);
}

使用dynamic_cast对类型进行迭代

 interface* base_ptr = ????;
 if(dynamic_cast<derived1*>(base_ptr))
     do_task_with_derived_1(dynamic_cast<derived1*>(base_ptr));
 if(dynamic_cast<derived2*>(base_ptr))
     do_task_with_derived_2(dynamic_cast<derived2*>(base_ptr));
 if(dynamic_cast<derived3*>(base_ptr))
     do_task_with_derived_3(dynamic_cast<derived3*>(base_ptr));
 //etc etc etc

或者形成一个type_id到函数的查找表。(或者更好的是,使函数成为虚成员)

static const std::unordered_map<std::type_id, std::function<void(interface*)> dispatcher =
    {
        {typeid(derived1), [](interface* p){
           do_task_with_derived_1(dynamic_cast<derived1*>(base_ptr);} },
        {typeid(derived2), [](interface* p){
           do_task_with_derived_2(dynamic_cast<derived2*>(base_ptr);} },
        {typeid(derived3), [](interface* p){
           do_task_with_derived_3(dynamic_cast<derived3*>(base_ptr);} },
    };
interface* base_ptr = ???;
dispatcher[typeid(*base_ptr)](base_ptr);