来自std::any的足够散列
C++ 中是否有足够的方法从 std::any 存储的数据中提取散列?好吧,或者至少是一个字节列表形式的对象及其长度
回答
std::any是一种类型安全机制,用于通过不需要知道该类型是什么的中介将已知类型的对象从一个位置传递到另一个位置。从中计算散列不是它的目标。事实上,如果不损害any的功能,这将是不可能的。
散列一个对象需要了解该对象正在做什么和正在做什么。假设您可以只查看对象表示的字节,从而从中计算出有意义的散列,结果不会很好。它可能看起来工作......一段时间。但最终,它会做错事。
您可以创建类似于any需要对象实现散列的类型擦除类型。但std::any不是那种类型,因为任何不想散列他们放入的类型的人都any无法将所述对象存储在any.
这是因为任何操作any提供的是一个操作,即是被存储到所有类型any必须也提供。例如,any是可复制的,因此any 不能存储仅移动类型。对于那些想要这样做的人来说,这是一个烦恼,并且您转储的功能any越多,该类型存储“任何”事物的能力就越受限制。
- @KonradRudolph: "*It’s entirely legitimate to want to use std::any as a dictionary key type*" No, it's legitimate to want to have a type-erased dictionary key type for hash containers. That `std::any` is meant to be or *ought to be* that type is another discussion entirely. I remind you that any functionality that `any` is required to have is functionality that all things you put into `any` *must have*. If `any` is hashable, then all types put into `any` must also be hashable. So even if I never use its hash functionality, my types must still be hashable.
- @KonradRudolph: `any` doesn't require the types in question to be equality-comparable, which is why `any` cannot be equality-compared. A statically typed language is simply not an appropriate place for some kind of omni-erased-type that can forward every operation to the type-erased object. Especially if you only want that functionality to be conditionally available.