Re: Why not add a feature to let lambda reference itself?
On Mar 12, 5:38 pm, Francis Glassborow
<francis.glassbo...@btinternet.com> wrote:
On 12/03/2012 01:48, Roman W wrote:
Thanks. But it is possible to define a new keyword for this purpose, for
example "self". If this was done when introducing the lambda functions
in C++, there would be no backward compatibility problem. If we wait,
there will be the question of existing correct code being broken by the
introduction of new keyword inside lambda functions.
Then the horse has already left the stable. I also suspect that WG21 would have big problems with introducing such a keyword as it is likely to be in wide use in existing code for whatever the individual programmer has chosen to use it for.
It's too late for C++11, but it's too early to close this chapter.
After all, polymorphic lambdas are also waiting its hour, so I guess
this topic will inevitably be revisited. Why not to take care of
recursion as well.
Though "self" isn't a good candidate, the Standard could reuse "this"
keyword with a different syntax, for example "[this]" or "[]this"
could refer to the most enclosed closure, "[[this]]" or "[][]this" can
refer to second-level object, and so on. Another possibility is to use
empty square brackets for even more pithy syntax, i.e. [] - first
level closure object, [[]] or [][] - second-level, etc. Below are some
examples with this invented syntax:
auto fact = [](unsigned n)
{
// [] referring to current closure
return n ? n * [](n - 1) : 1;
};
auto fact1 = [](unsigned n)
{
// [[]] referring to the second level "this"
// compilation error if not used in a proper context
return n ? n * [[]](n - 1) : 1;
};
auto fact2 = [](unsigned n)
{
return fact1(n); // ok, [[]] refers to this closure
};
auto fact3 = [](unsigned n)
{
// same
return [=]{ return n ? n * [[]](n - 1) : 1; }();
};
struct A {
// now let's make another step
// and allow in-class lambda initialization
auto fact { [](unsigned n) { return n ? n * [](n - 1) : 1; }};
};
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]