Boost logo

Boost Users :

Subject: Re: [Boost-users] chaining functions input output
From: Nathan Ridge (zeratul976_at_[hidden])
Date: 2013-02-18 17:40:53


> > >> i have these 2 functions provided to me and I wonder whether they can
> > >> somehow be chained without using intermediary memory?
> > >>
> > >> http://codepad.org/tTwkUQhp
> > >
> > > No.
> > > You have to supply a range [begin..end) for fun2(), so this range
> > > should be prepared first.
> > >
> > someone mentioned boost.coroutine could help in this case?
>
> I'm the one who mentioned that, and yes, it is possible :)
>
> Basically, one can use coroutines to implement a generic outputs_of()
> function that takes a unary function whose argument is an output
> iterator, and returns a range representing all the values passed to
> this output iterator, without storing them all.
>
> You would call it like this:
>
> fun2(outputs_of(bind(fun1, input, _1)), output)
>
> I actually wrote such a function, but using an earlier version of
> the coroutine library (back when the coroutine functionality was
> still in Boost.Context). I am planning to update my implementation
> after the interface of Boost.Coroutine is stabilized (it is
> currently under review on the dev list). I am happy to post it
> once I've done that

Turns out that the final version of Boost.Coroutine that made it
into the 1.53 release has out-of-the-box support for treating the
values returned by a coroutine as a range, which makes writing such
an outputs_of() function trivial:

using boost::coroutines::coroutine;
...
template <typename T, typename F>
coroutine<T()> outputs_of(F f)
{
    return coroutine<T()>{[f](typename coroutine<T()>::caller_type& caller)
    {
        f(boost::make_function_output_iterator([&caller](const T& t){ caller(t); }));
    }};
}

A complete example using the two functions in your original post is
attached.

The code uses some C++11 features like lambdas, but these can
easily be translated to their C++03 equivalents if necessary.
I'll leave it to you as an exercise to do that if you need to.

Hope that helps!

Regards,
Nate
                                               



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