Boost logo

Boost Users :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2005-10-04 22:54:02


Duane Murphy writes:

> How do I iterate over a type list and call a function? MPL?
>
> I have a base class BASE that has several subclasses A, B, C that have
> special capabilities, but no way to identify those capabilities aside
> from the type.
>
> I would like to determine if an object of type BASE is also of one of
> the special subclasses:
>
> ie
> void f( BASE* base)
> {
> if ( dynamic_cast< A* >( base ) != NULL )
> {
> some_function( dynamic_cast< A* >( base ) );
> }
> else if ( dynamic_cast< B* >( base ) != NULL )
> {
> some_function( dynamic_cast< B* >( base ) );
> }
> else if ( dynamic_cast< C* >( base ) != NULL )
> {
> some_function( dynamic_cast< C* >( base ) );
> }
> }
>
> I think you can see why I'd like a type list iterator solution to this.

Try this:

    struct do_something
    {
        do_something( BASE* base ) : m_base( base ) {}

        template< typename T > void operator()( mpl::identity<T> ) const
        {
            if ( T* x = dynamic_cast< T* >( this->m_base ) )
                some_function( x );
        }

        BASE* m_base;
    };

    mpl::for_each<
          mpl::vector<A,B,C>
        , mpl::make_identity<_1>
>( do_something( base ) );

>
> I have arranged for the some_function to be a template as well to make
> things easier.
>
> What I am looking for is the equivalent of find_if() but for types and
> done at run time. I looked over MPL, but MPL seems to apply at compile
> time without a door to the run time world. :-)

Not true :), but 'for_each' is indeed not documented at the moment.

-- 
Aleksey Gurtovoy
MetaCommunications Engineering

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net