C++11 - typeid 唯一性

C++11 - typeid uniqueness

在 C++11 中,我正在使用这个

typeid(T).name()

用于我自己的哈希计算。我不需要程序运行或编译之间的结果相同。我只需要它对于类型是唯一的。 我知道,它可以 return 不同类型的相同名称,但它通常与 const、指针等一起使用。 在我的例子中,T 只是 class XYstruct XX 或派生类型。

在这种情况下,我可以假设 T 是唯一的吗?

std::type_info::name 是实现定义的,因此您不应该依赖它对于不同类型是唯一的。

由于您这样做是为了哈希计算,因此您应该改用 std::type_info::hash_code。尽管这不能保证 值是唯一的,但该标准表示实施应该尝试 return 不同类型的不同值。只要您的哈希映射实现具有合理的冲突处理,这对您来说就足够了。

cppreference 所述:

Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.

所以,不,你不能。实际上你不能假设任何事情。

虽然,hash_code() 给你:

size_t hash_code() const noexcept;

7 Returns: An unspecified value, except that within a single execution of the program, it shall return the same value for any two type_info objects which compare equal.

8 Remark: an implementation should return different values for two type_info objects which do not compare equal.

也就是说hash_code()只有在operator== for type_info支持的情况下才能区分两种不同的类型。

您应该使用 std::type_index 进行映射。

The type_index class is a wrapper class around a std::type_info object, that can be used as index in associative and unordered associative containers. The relationship with type_info object is maintained through a pointer, therefore type_index is CopyConstructible and CopyAssignable.

您可以做的是获取会员的地址。

class HashBase {
    virtual intptr_t get() = 0;
};

template <typename T>
class Hash : HashBase {
    static const int _addr = 0;
    intptr_t get() override { return reinterpret_cast<intptr_t>(&_addr); }
};