Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2003-02-14 08:31:02


Jonathan Wang wrote:
> Hi,

Hi Jonathan,

>
> The "for-each" in mpl is used to generate codes, which apply some
> function to each element in a sequence. Well, I wonder if there
> could be more generators, "select"(a better name?) for example.

Easily, 'for_each' is just the one that happened to cover all our
use cases, till now.

> "select" is used to apply some function to a specified element in a
> sequence(the case in the FSM example, not each element). So it could
> be used to generate codes like the "if-else/switch" structure. Here's
> an example.

[snip the code]

Hmm, interesting. So, basically, the "select" has the semantics of
"mixed" (half run-time, half compile-time) 'find_if' - it takes
a compile-time sequence and a run-time predicate, and iterates the
former until the predicate is satisfied (or it reaches the end of the
sequence). We can "return" the search result by passing another
function object that will be called when something is found:

    // untested!
    template< typename T, long N >
    struct pred
    {
        pred(T (&a)[N], T const& value)
            : a_(a)
            , value_(value)
        {
        }

        template< typename I >
        bool operator()(I index) const
        {
            return this->a_[index] == this->value_;
        }

        T (&a_)[N];
        T const& value_;
    };

    template< typename T, long N >
    T*
    find(T (&a)[N], T const& value)
    {
        // here:
        long i = N;
        mpl::find_if_< mpl::range_c<int,0,N> >(
              pred<T,N>(a, value)
            , ll::var(i) = _1
            );

        return &(a[i]);
    }

    int main()
    {
        double X[5] = { 1.0, 2.1, 3.5, 6.6, 5.4 };
        std::cout << *find(X, 3.5);
    }

Does it make sense to you?

Aleksey


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