使用shared_ptr时获取子类的type_info

Get type_info for subclass when using shared_ptr

本文关键字:type 子类 info shared ptr 使用 获取      更新时间:2023-10-16

我有下面的最小示例代码。我希望能够在Application::HandleEvent方法中确定Derived类。

Application类最终将包含一个map,它将type_info映射到一个处理程序函数(我知道如何使用operator<),以将事件路由到它们的特定处理程序。

使用带有原始指针的多态性做这件事没有问题,但如果将shared_ptr引入到混合中,我就无法做到这一点。

它总是报告type_info是基类的,无论我使用shared_ptr的type_info(智能指针不是多态相关的,这并不奇怪)还是使用.get()的指向类的type_info

这可能吗?我不是在寻找在事件子类本身中定义处理程序方法的解决方案。

#include <typeinfo>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
class Event
{
    public:
    virtual ~Event(){};
};
class SpecificEvent1 : public Event
{};
class SpecificEvent2 : public Event
{};
class Application
{
    public: 
    void HandleEvent(boost::shared_ptr<Event> e)
    {
        std::cout << typeid(e.get()).name() << "n";
        std::cout << typeid(e).name() << "n";
    }
};
int main(int, char**)
{
    Application app;
    boost::shared_ptr<SpecificEvent1> se1 = boost::make_shared<SpecificEvent1>();
    boost::shared_ptr<SpecificEvent2> se2 = boost::make_shared<SpecificEvent2>();
    app.HandleEvent(se1);
    app.HandleEvent(se2);
}

当您在指针上使用typeid时,您得到的是关于指针的信息,而不是底层对象的信息。要获得与多态指针对应的底层对象的信息,请使用引用,即取消引用指针

代替

std::cout << typeid(e.get()).name() << "n";

使用

std::cout << typeid(*e).name() << "n";