可以使用type_info指针来区分C ++中的类型吗? [英] Can type_info pointers be used to distingush types in C++?

查看:181
本文介绍了可以使用type_info指针来区分C ++中的类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组多态C ++类,它们都由同一个模块(Windows DLL)实例化.现在有两个指向此类的指针,并调用了typeid:

I have a set of polymorphic C++ classes and they are all instantiated by the same module (Windows DLL). Now having two pointers to such classes and having called typeid:

SomeCommonBase* first = ...; //valid pointer
SomeCommonBase* second = ...; //valid pointer
const type_info& firstInfo = typeid( first );
const type_info& secondInfo = typeid( second );

我可以比较检索到的type_info地址

can I compare retrieved type_info addresses

if( &firstInfo == &secondInfo ) {
   //objects are of the same class
} else {
   //objects are of different classes
}

或使用==

if( firstInfo == secondInfo ) {
   //objects are of the same class
} else {
   //objects are of different classes
}

检测对象是(完全)同一类还是不同类?从同一模块内实例化对象时是否可以保证正常工作?

to detect whether objects are of (exactly) the same class or of different classes? Is it guaranteed to work when objects are instantiated from within the same module?

推荐答案

在我撰写本文时,您的代码是

As I'm writing this, your code is

SomeCommonBase* first = ...; //valid pointer
SomeCommonBase* second = ...; //valid pointer
type_info& firstInfo = typeid( first );
type_info& secondInfo = typeid( second );

它不应编译,因为typeid返回对const的引用.

It should not compile because typeid returns a reference to const.

更糟糕的是,您正在询问有关指针的类型信息.这两个指针的类型均为SomeCommonBase*,因此可以确保它们具有相同的类型.而是询问有关所指向对象的类型信息.

Worse, you are asking for type info about the pointers. Both pointers are of type SomeCommonBase*, so you're guaranteed that they are of the same type. Ask instead for type info about the pointed to objects.

也就是说,正如@DeadMg所说,您还需要使用operator==比较类型信息对象.

That said, as @DeadMg remarked, you also need to use operator== to compare type info objects.

C ++标准未解决动态库的问题.但是在任何给定的Windows模块中,您都应该是安全的.

The C++ standard does not address the issue of dynamic libraries. But within any given Windows module you should be safe.

干杯hth.,

这篇关于可以使用type_info指针来区分C ++中的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆