Boost logo

Boost :

From: Jody Hagins (jody-boost-011304_at_[hidden])
Date: 2004-12-06 15:32:07


On Sat, 4 Dec 2004 23:44:46 -0700
"Jonathan Turkanis" <technews_at_[hidden]> 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.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk