Domanda

Somewhere during the forming of the new standard there was a promise for easier type_info usage, which among others resulted in the implementation of hash_code. Implementing a reflection system in C++11 however I ran into a problem with unique type identification again.

I need:

  1. Something that will allow me extraction from a type using typeid a unique identifier
  2. The unique identifier needs to be able to be used in a key/value container
  3. The identifier does not need to be portable, nor even the same between program executions

Note that I do not need persistence between program exeutions. As it seems:

  1. .name() is completely useless, because the standard gives no guarantees on it whatsoever.
  2. .hash_code() is also useless because it's not guaranteed to be unique
  3. Taking a pointer to the type_info object won't work everywhere (across DLL's for example)
  4. Only .before() seems to be useful - although I don't know if it wouldn't suffer from the same problem as #3

Even if .before() is to be used, then we can use map, while I would prefer to use unordered_map.

struct compare_type_info {
    bool operator ()(const type_info* a, const type_info* b) const {
        return a->before(*b);
    }
};
std::map<const type_info*, X, compare_type_info> map;
m[&typeid(int)] = something;

Is the above safe for collision? Does the ordering operator guarantee overwrite of !< and !> values?

Is there a way to solve this problem without hash collision risk?

In terms of rolling up my own type system, I already do that, but typeid solves problems with giving the proper final type from a base type (inheritance) and I do not want to add any fields to my classes (the type system is "external").

Even in C++11 are we still screwed? :/

È stato utile?

Soluzione

You can use std::type_index, which is constructable from a std::type_info. These are fully ordered, implementing all of the relational operations. A type_index is even implicitly convertible from type_info.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top