Boost logo

Boost Users :

Subject: [Boost-users] [MPL] searching a vector at runtime
From: Alexander Lamaison (awl03_at_[hidden])
Date: 2010-05-15 22:42:14


I'm trying to recursively traverse an MPL vector_c but I'm not sure what
the base-case type should be.

I want to pick a type from a mpl::vector at runtime and use it to dispatch
a call to an overloaded function. Basically tag-dispatch with the tags
being looked up in an MPL collection.

The runtime value is an unsigned it so I just store unsigned ints in a
vector_c. Then I want to traverse this vector and compare each item to the
runtime value. If I find a match, I want to use it to call an overloaded
function. Here's how I'm trying to do it so far:

template<typename ID>
class message { ... }

template<typename Sequence> // MAP is a vector_c
struct dispatcher
{
  template<typename T>
  static result dispatch(T* obj, unsigned int message_id, int arg)
  {
    typedef boost::mpl::front<Sequence>::type head;
    typedef boost::mpl::pop_front<Sequence>::type tail;

    if (head::value == message_id)
        return obj->handle(message<head::value>, arg);
    else
        return dispatcher<tail>::dispatch(obj, message_id, arg);
  }
};

template<>
struct dispatcher<boost::mpl::void_> // WHAT SHOULD THIS TYPE BE?
{
  template<typename T>
  static result dispatch(T* obj, unsigned int message_id, int arg)
  {
      return obj->default_message_handler(message_id, arg);
  }
};

struct handler
{
  result handle(message<MESSAGE1>) { /* do stuff 1 */ }
  result handle(message<MESSAGE2>) { /* do stuff 2 */ }
  result default_message_handler(unsigned int id, int arg) {}
}

I'm stuck on what to make the dispatcher base case which is reached when
pop_front is called on a list with one item. At first I though the
resulting type was void_ but apparently this doesn't match.

I'm new to MPL. Can someone explain what I'm doing wrong here or if
there's an altogether better way?

Many thanks.

Alex Lamaison


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