
"Duane Murphy" <duanemurphy@mac.com> 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.
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. :-)
If you read the chapter 11 of C++ Template Metaprogramming (http://boost-consulting.com/mplbook/#table-of-contents-and-sample-chapters), you'll learn about the approach for doing this. Something like: struct do_nothing { void operator()() const {}; } template <class T, class NextFunctionType> struct try_derived_class { void operator()(base* b) const { if (T* d = dynamic_cast<T*>(b)) { some_function(d); } else { NextFunctionType f; f(b); } } }; mpl::fold< a_sequence_of_derived_classes , try_derived_class<_2,_1> , do_nothing
dispatch;
Now dispatch is a function object that does your thing. -- Dave Abrahams Boost Consulting www.boost-consulting.com