[Effective-cpp] Item 1: Uses and Abuses of vector

Terje Slettebø tslettebo at broadpark.no
Wed Oct 27 01:40:18 EDT 2004


>From: "Herb Sutter" <hsutter at microsoft.com>

> >> I agree, Lambda is a marvellous use of templates but I'd far rather
> the
> >> language supported it directly.
> >
> >How would you like this language support to look like? I.e. how would
> you
> >write my for_each() example, with language support for lambda
> functions?
>
> If you mean a general for_each, I'd like to replace code like
>
>   for( iter = v.begin(); iter != v.end(); ++ iter {
>     do stuff with iter
>   }
>
> with
>
>   for_each( v.begin(), v.end(), lambda (i) {
>     do stuff with i
>   });
>
> That is, each algorithm becomes a directly usable looping construct.

Fair enough. That looks quite good.

> If you meant:
>
> >vector<int> v;
> >int x, y;
> >...
> >find_if(v.rbegin(), v.rend(), bind2nd(greater_equal<int>(), y));
> >
> >This may be written using BLL as:
> >
> >find_if(v.rbegin(), v.rend(), _1 >= y);
>
> then I'd like to be able to write it as:
>
>   find_if( v.begin(), v.end(), lambda (i) { return i >= y; } );
>
> Now you get into closures (how to capture y, etc.). So that syntax
> probably isn't exactly what we'd get, but that's the idea. Better still,
> it could be nice to have the current lambda syntax supported as a
> convenience shorthand for the simpler lambda functions:
>
>   find_if( v.rbegin(), v.rend(), _1 >= y );
>
> but with compiler/language support and good error messages, not deeply
> weird messages about deep template machinery.

With support for concepts in one form or another, this might be improved
even for a library solution.

Besides, there doesn't have to be an either-or, as C++0x is several years
off, and libraries, like BLL, gives us some experience working with things
like this, which may be valuable if one is to add core language support for
it (you mentioned handling of closures, for example).

Support for concepts (which I think may be the next big thing in C++) is
another area where core language support is really needed to get full
support for it, but where we even today may get quite a bit of the benefits,
and experience with it, using a library solution (like Boost Concept Check
Library, or enable_if + type traits).

Regards,

Terje




More information about the Effective-cpp mailing list