Boost logo

Boost Users :

Subject: [Boost-users] [MPL] Proposal for runtime_contains_if algorithm submission
From: Eldar Kononov (ekononov_at_[hidden])
Date: 2010-04-26 08:57:22


Hello everyone.

Currently only one runtime algorithm is available in MPL: for_each.

I suggest to add another one: runtime_contains_if.

The problem is searching through the sequence of types and find that
one which satisfies some runtime predicate.

Sample task:

Given some base abstract class:

struct base
{
  virtual ~base(){}
};

The implementation of the base could be one of the following classes:

struct child1 : public base {};
struct child2 : public base {};
struct child3 : public base {};
struct child4 : public base {};
struct child5 : public base {};

Now suppose you have "base* b" and you need to find out if its
concrete type is either child3 or child4 (in practise the set of types
to check could be larger).

I propose the following solution:

1. You write a predicate similar to STL contains_if but with template
type in operator(). The concept is the same as in
boost::mpl::for_each.

struct child_detector
{
   base* base_;
   child_detector( base* b ) : base_( b ) {}

   template< typename Derived_ >
   bool operator()( Derived_* )
   {
       return ( 0 != dynamic_cast< Derived_* >( base_ ) );
   }
};

2. You use boost::mpl::runtime_contains_if algorithm:

bool type_is_special( base* b )
{
    typedef boost::mpl::list< child3, child4 > special_types;
    return boost::mpl::runtime_contains_if< special_types >(
        child_detector(b) );
}

The implementation of the boost::mpl::runtime_contains_if
is in attached runtime_contains_if.hpp.

Complete example is in attached runtime_contains_if_example.cpp.





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