Boost logo

Boost :

From: Jaakko Jarvi (jajarvi_at_[hidden])
Date: 2004-03-08 10:34:06


On Sun, 8 Mar 2004, Gabriel Dos Reis wrote:

> Jaakko Jarvi <jajarvi_at_[hidden]> writes:
>
> | My example was a bit contrived too.
> | Here's another example (with imaginary syntax):
> |
> | auto foo() {
> | int i;
> | return auto(int x) { return i + x; }
> | }
>
> Is it different from
>
> int& f() { int i; return i; }
>
> ?
>
>
> In -a- model I discussed a while ago with the second author of
> decltype/auto proposal, lambdas are unnamed constants that can be
> implemented by local classes. The body of the lambda would be
> forwarded-to by the appropriate overload of the call operator,
> i.e. your example would be
>
> foo: () -> auto {
> int i;
>
> struct xxx {
> operator(): (int x) -> auto { return i + x; }
> };
> };
>
> That is a very simple model that just provides a syntactic sugar
> (modulo use of auto in return type) for what you can do in current
> C++. In particular, it is clear that the reference to "i" is a hard
> error by application of current rules governing local classes.

Right, variables with local storage cannot be used in local classes.
Now this rule would forbid the above (which is good), but it would also
rule out useful and safe lambdas:

  auto foo(int x, int y) {
    int i = x+y; // just some computation to motivate a local variable
    vector<int> v;
    ...
    transform(v.begin(), v.end(), v.begin(),
                auto(int x) { return x+i; });
  }

Which you can currently write using BLL as:

  transform(v.begin(), v.end(), v.begin(), _1 + i);

(BLL stores a copy to i internally)

   Jaakko


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