How to loop through a boost::mpl::list?
Asked Answered
S

1

9

This is as far as I've gotten,

#include <boost/mpl/list.hpp>
#include <algorithm>
namespace mpl = boost::mpl;

class RunAround {};
class HopUpAndDown {};
class Sleep {};

template<typename Instructions> int doThis();
template<> int doThis<RunAround>()    { /* run run run.. */ return 3; }
template<> int doThis<HopUpAndDown>() { /* hop hop hop.. */ return 2; }
template<> int doThis<Sleep>()        { /* zzz.. */ return -2; }


int main()
{
    typedef mpl::list<RunAround, HopUpAndDown, Sleep> acts;

//  std::for_each(mpl::begin<acts>::type, mpl::end<acts>::type, doThis<????>);

    return 0;
};

How do I complete this? (I don't know if I should be using std::for_each, just a guess based on another answer here)

Stav answered 15/5, 2010 at 15:28 Comment(0)
W
14

Use mpl::for_each for runtime iteration over type lists. E.g.:

struct do_this_wrapper {
    template<typename U> void operator()(U) {
        doThis<U>();
    }
};

int main() {
    typedef boost::mpl::list<RunAround, HopUpAndDown, Sleep> acts;
    boost::mpl::for_each<acts>(do_this_wrapper());    
};
Waldack answered 15/5, 2010 at 15:30 Comment(4)
Thanks - is there a way to do this using boost::bind instead of the wrapper object?Stav
@Kyle: I don't think so - i'm not aware of any utility in Boost.Bind that generates you the required functors with a templated operator().Waldack
@GeorgFritzsche: Is there a way of making do_this_wrapper a lambda (as of C++11/14/17)?Hattie
@AdiShavit That should be possible with C++14s generic lambdas.Waldack

© 2022 - 2024 — McMap. All rights reserved.