通过 typeid 的类的数字唯一标识符
C++ 中的 typeid 运算符返回 std::type_info 类的对象,该对象可以生成其文本名称。但是,我只是想为任何多态类获取唯一的数字标识符。 (在单个程序运行的范围内是唯一的 - 不一定在运行之间)
在实践中,我可以取消引用指针并读取 vptr
的内容 - 但这会既不优雅也不便携。我更喜欢便携式方式。
我可以使用 typeid
运算符以某种方式为类提供“安全”数字标识符吗?例如,对于给定类的每个 typeid
调用,我是否可以指望生成的 std::type_info
结构的地址相同?或者也许是 name()
指针本身?
The typeid
operator in C++ returns an object of class std::type_info
which can yield its textual name. However, I'm just interested in getting an unique numeric identifier for any polymorphic class. (unique in the scope of a single program run - not necessarily between runs)
In practice, I could just dereference the pointer and read the vptr
's contents - but this would be neither elegant nor portable. I prefer a portable way.
Can I use the typeid
operator somehow to have a "safe" numerical identifier for a class? For example, can I count on the address of resulting std::type_info
structure to be the same for every typeid
call on a given class? Or perhaps the name()
pointer itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
std::type_index (C++ 11) 可用于容器中基于类型存储值。但它不会给你一个数字。
更多: http://en.cppreference.com/w/cpp/types/type_index< /a>
std::type_index (C++ 11) can be used in containers to store values based on type. It won't give you a number though.
More: http://en.cppreference.com/w/cpp/types/type_index
type_info 有一个运算符==(),用于将它描述的类型与另一个 type_info 对象的类型进行比较。这些对象也保证比程序更长寿。
因此,如果您保存两个 type_info 的地址,您可以使用 *p1 == *p2 来查看它们是否引用相同的类型。
The type_info has an operator==() for comparing the type it describes to the type of another type_info object. The objects are also guaranteed to outlive the program.
So if you save the addresses of two type_infos, you could get away with
*p1 == *p2
to see if they refer to the same type.使用计数器的算法初始化的静态数据成员?然后使用 MyClass::id 作为唯一标识符。然后使用虚函数根据基类获取唯一标识符。保证可移植,但有轻微的维护负担,因为您需要为创建的每个新类实现静态变量和虚函数。但我猜这不是一个大问题,因为您已经选择使用 c++,众所周知,c++ 很冗长。它看起来像这样:
static data member that is initialized with an algorithm that uses a counter? Then use MyClass::id as the unique identifier. And then use virtual functions to fetch the unique identifier based on baseclass. Guaranteed to be portable, but has slight maintainance burden since you need to implement both the static variable and implement the virtual function for every new class you create. But guess that's not a big problem since you've already chosen to use c++, which is known to be verbose. It would look like this:
看起来 type_info::hash_code() 是为 C++0x 规定的。
Looks like type_info::hash_code() is prescribed for C++0x.