使用shared_ptr时获取子类的type_info
Get type_info for subclass when using shared_ptr
我有下面的最小示例代码。我希望能够在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";
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 避免在C++中重复子类定义
- 将QOpenGLWidget子类转换为使用Metal而不是OpenGL的子类是否可行?
- 如何初始化矢量的模板化子类
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 使用子类覆盖基类中定义的函数
- 子类地址等于虚拟基类地址?
- 将子类方法声明为基类的友元
- C++子类共享变量?
- 如何检查模板专用化是否是基本模板的子类?
- 仅让特定类'Fabric'构造类'Foo'及其所有子类的实例
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 如何在C++子类中访问父类的私有变量
- 将父类的子类的数据复制到具有相同父类的另一个类