Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2003-01-22 20:10:41


"Andrei Alexandrescu" <andrewalex_at_[hidden]> writes:

> Or (barring my lack of mastering some syntactic details):
>
> inline void do_my_function(string&, void_) {}
>
> template <class Lst>
> inline void do_my_function(string& s, Lst lst)
> {
> my_function<front<Lst>::type>(s);
> do_my_function(s, pop_front<Lst>::type());
> }
> ...
> do_my_function(s, my_list());
>
> No struct, no for_each, no operator(). Et que le meilleur gagne :o).

Yeah, I haven't always been very comfortable with the
value-per-character of mpl::for_each -- it seems to have similar
properties to std::for_each in that way. It's got certain advantages
for re-use:

   1. You can use different sequence types (I know Andrei doesn't buy
      this one, but I still do; the concept of tuple-as-type-sequence
      being one motivator)

   2. If you want to invoke the function on different transformations
      of the type sequence, the optional lambda (2nd template)
      parameter lets you do that without writing the loop all over
      again.

But those aren't hugely compelling for me.

In the end I still use mpl::for_each because of the way it separates
concerns: it's nice to have to think only about what type
transformation to make and how to invoke the runtime action, and not
have to worry about traversing the sequence. This isn't quite the
same deal as with the STL, where it's nearly always better to write a
for loop. Unlike the for loop, the recursive formulation isn't just
mindless recognizable boilerplate because the presence of parameters
changes the form and because of the non-locality of the termination
condition. Some people may have an easier time mentally with that
than I do, but for me it's still clearer and easier to use
mpl::for_each.

I've been talking with Aleksey recently about how to improve the
syntactic situation without losing the separation of concerns that we
get, but we didn't come up with anything convincingly better. I think
a long time ago the for_each parameter used to look like:

    class f
    {
        template <class T>
        struct apply
        {
            static void execute() {...};
        };
    };

IOW, a metafunction class with a nested 'execute' function. However
that's not really any better syntactically, it has problems carrying
state, and it's anti-idiomatic.

-- 
                       David Abrahams
   dave_at_[hidden] * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk