I’m still working on a good solution to my One-Of-A-Type Container Problem — and upon reflection I think it would be nice to be able to just use something like a std::map<std::type_info, boost::any>. Unfortunately, std::type_info does not define an operator<, and I think it’d be unreasonable for it to define one.
However, it does seem reasonable to define a hash function for it, because you could simply use the singleton address of the std::type_info object as a reasonable “hash”. Therefore, you’d be able to put a std::type_info into a std::unordered_map as the key.
Does C++11 provide such a hash function? Would using the memory address of the std::type_info singleton be a bad hash strategy?
The fact that
type_infois not less-than comparable isn’t as much a problem for using it as a map key as the fact thattype_infois non-copyable. 🙂In C++03,
type_infohas abefore()member function that provides an ordering oftype_infoobjects.In C++11,
type_infohas ahash_code()member function (C++11 §18.7.1/7):type_infoobjects resulting from thetypeidoperator exist until the end of the program, so it is safe to use atype_info*as a map key. However, to the best of my knowledge, there is no guarantee that if you applytypeidto two objects of the same type you will get two references to the sametype_infoobject.If you do use
type_info*as a map key, I’d use a custom comparator that dereferences the pointers and compares thetype_infoobjects themselves (using the aforementionedbefore()orhash_code()for ordering).