
On Sat, 4 Dec 2004 23:44:46 -0700 "Jonathan Turkanis" <technews@kangaroologic.com> wrote:
You don't need typeid -- you can just do:
template<typename T> struct unique_id_holder { static char val; };
template<typename T> char unique_id_holder::val;
template<typename T> int unique_id() { return reinterpret_cast<int>(&unique_id_holder::val); }
For "better" portability, you should make that "int" a "long." Also, note that the following assertions will be true... struct Foo { }; assert(typeid(Foo) == typeid(Foo)); assert(typeid(Foo) == typeid(Foo &)); assert(typeid(Foo) == typeid(Foo const)); assert(typeid(Foo) == typeid(Foo const &)); long tid[4]; tid[0] = unique_id<Foo>(); tid[1] = unique_id<Foo &>(); tid[2] = unique_id<Foo const>(); tid[3] = unique_id<Foo const &>(); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { if (i == j) { assert(tid[i] == tid[j]); } else { assert(tid[i] != tid[j]); } } } which is probably obvious to some, but not all, and the implications are possibly a bit more subtle. Specifically, each of the above will get a different ID when calling unique_id<T>() with modifiers and references, but they will get the "same" std::type_info for those calls.