Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2003-01-23 22:21:09


David Abrahams wrote:
> Terje Slettebø <tslettebo_at_[hidden]> writes:
> > Perhaps it might be possible to do some compile-time/run-time lambda
> > (similar to Boost.Lambda for runtime, and MPL's lambda), so you
> > could do something like:
> >
> > mpl::for_each<my_list>(my_function<_>(s));
> >
> > It would then transform the function call "my_function<_>(s)" into
> > an instantiated function object of the kind suitable for
> > mpl::for_each.
>
> I'm afraid that particular syntax won't work for this particular case,
> though. If my_function is a function template, my_function<_> is a
> function, and my_function<_>(s) calls that function.
>
> Since there are no (function template) template parameters, only
> (class template) template parameters, there doesn't appear to be any
> way to make this one particularly easy except by using the
> preprocessor to define some kind of function object.
>
> It appears to be just bad luck that higher order functional
> programming with function templates is impossible in C++.

My current understanding (which, admittedly, is not backed up by a
real-world experience) is that if you care about higher-orderness of your
generic algorithms, a preferred implementation construct for those
algorithms is not a function template, but a static _function object_ (a
technique used in FC++):

    struct my_function_
    {
        template< typename U >
        void operator()(std::string const& text, U)
        {
            // ...
        }

    } my_function; // here!

For ordinary uses, the above will act just like a plain function template
(minus ADL/explicit template arguments specification):

    my_function("text", int());

and it will also allow one to do something like this:

    std::string text("text");
    mpl::for_each< my_types >(boost::bind<void>(my_function, text, _1));

Aleksey


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