Boost logo

Boost :

From: Mathias Gaunard (mathias.gaunard_at_[hidden])
Date: 2008-03-28 14:26:36


Boost.variant provides visitation over an object whose types is within a
certain set.
To identify the type of the object, it uses an additional int that
uniquely identifies the type of the object within the set.

However, RTTI already provides unique identification for objects of
polymorphic types within all types.

I'm well aware that typeid(SomeType) is not a constant expression (which
is quite a shame really, especially since I can't see any technical
reason why it couldn't be) but it is still possible to do something like
this:

switch(typeid(o).name()[0])
{
    case 'F':
        switch(typeid(o).name()[1])
        {
            case 'o':
                switch(typeid(o).name()[2])
                {
                     case 'o':
                         switch(typeid(o).name()[3])
                         {
                             case 0:
                                 // object of type "Foo"
                                 break;

                              default:
                                 // unknown type
                         }
                     default:
                         // unknown type
                }
            default:
                // unknown type
        }
    default:
        // unknown type
}

By providing the name of the types as a compile-time string, it could be
possible to generate the implementation-specific mangled name and, from
it, this kind of switch statement.
This would allow O(1) (but with a possibly large constant) visitation of
objects of polymorphic types non-intrusively.

An utility could provide something like this:

struct Base { virtual ~Base() = 0; };

struct Derived1 : Base { virtual Derived1() {} };
struct Derived2 : Base { virtual Derived2() {} };
struct Derived3 : Base { virtual Derived3() {} };

typedef mpl::map<
     mpl::pair<
         mpl::string<'D', 'e', 'r', 'i', 'v', 'e', 'd', '1'>,
         Derived1
>,
     mpl::pair<
         mpl::string<'D', 'e', 'r', 'i', 'v', 'e', 'd', '2'>,
         Derived2
>,
     mpl::pair<
         mpl::string<'D', 'e', 'r', 'i', 'v', 'e', 'd', '3'>
         Derived3
>
> derived_types;

struct Visitor
{
     typedef void result_type;

     template<typename T>
     void operator()(T&) const
     {
         // something useful
     }
};

// b can actually be of any type derived from Base
void foo(const Base& b) const
{
    poly_visit<derived_types>(b, Visitor());
}

Is there some interest in such a tool?


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