简体   繁体   English

可以使用 type_info 指针来区分 C++ 中的类型吗?

[英]Can type_info pointers be used to distingush types in C++?

I have a set of polymorphic C++ classes and they are all instantiated by the same module (Windows DLL).我有一组多态 C++ 类,它们都由同一个模块(Windows DLL)实例化。 Now having two pointers to such classes and having called typeid :现在有两个指向此类类的指针并调用了typeid

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

can I compare retrieved type_info addresses我可以比较检索type_info地址吗

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

or use ==或使用==

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?检测对象是否(完全)相同的 class 或不同的类? Is it guaranteed to work when objects are instantiated from within the same module?当对象从同一个模块中实例化时,它是否保证工作?

You can only retrieve const type_info references, and you should always use operator== .您只能检索const type_info 引用,并且应该始终使用operator==

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 );

It should not compile because typeid returns a reference to const .它不应该编译,因为typeid返回对const的引用。

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.两个指针都是SomeCommonBase*类型,因此可以保证它们是相同的类型。 Ask instead for type info about the pointed to objects.而是询问有关指向对象的类型信息。

That said, as @DeadMg remarked, you also need to use operator== to compare type info objects.也就是说,正如@DeadMg 所说,您还需要使用operator==来比较类型信息对象。

The C++ standard does not address the issue of dynamic libraries. C++ 标准没有解决动态库的问题。 But within any given Windows module you should be safe.但是在任何给定的 Windows 模块中,您应该是安全的。

Cheers & hth.,干杯&hth.,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM