I have class Base
and classes Derived_1
, Derived_2
...
I need derived classes to have an id. Those ids are used for further lookups et
C++11 solves this by providing std::type_index
, in <typeindex>
, which is a copyable, comparable and hashable object constructed from a std::type_info
object that can be used as the key in associative containers.
(The implementation is fairly simple, so even if you don't have C++11 yourself, you could steal the implementation from, say GCC 4.7, and use that in your own code.)
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
typedef std::unordered_map<std::type_index, int> tmap;
int main()
{
tmap m;
m[typeid(main)] = 12;
m[typeid(tmap)] = 15;
}
You can use typeid(object)
directly, since there is type_info::before
, which can be used as comparator if you use type_info as key in the map, see What is `type_info::before` useful for?. No need to get .name()
.
You can use whatever type or class you want as the key to std::map
, provided you give the template arguments a compare function that tells it how to sort the underlying tree.
The easiest thing to do IMHO to represent dates as keys, is to convert them to unix timestamps, but no matter what the class representation of them may be, just provide a comparison function to the map's definition and you're good to go.