c++ 我需要在结构中存储具有继承和虚函数的各种类之间的对象"type"
c++ I need to store in a structure the "type" of an object among various classes with inheritance and virtual functions
我用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);
相关文章:
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 填充上编译器生成的复制构造函数之间的不一致
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 如何在"push_*()"和"emplace_*()"函数之间进行选择?
- 仅具有运算符()的结构和普通函数之间的实际区别
- 当两者都调用时,删除和析构函数之间的区别?
- Release() 和析构函数之间的区别?
- 调用 "project" 函数和调用 DLL 函数之间的区别
- C++模板和非模板函数之间的重载解析
- std::shared_ptr 和 std::unique_ptr 构造函数之间的不对称
- C++ 和 Lua 函数之间的交互与 3D 矢量参数
- 在结构函数之间传递文件路径 C++ 编辑:修复LNK2019错误
- 在C++同名的顶级函数之间进行选择
- 在成员函数之间传递const变量为数组的索引
- Helgrind 报告了使用 Singleton 及其构造函数之间可能存在的竞争
- 函数模板和函数之间奇怪的不一致"normal"
- 在c#和c函数之间传递值和指针
- 在C++中调用 malloc() 与"operator new"函数之间的实现差异
- 在函数之间传递相同的数组
- C++编译错误是由于使用 std::move 时运动构造函数与其他非运动构造函数之间的冲突