Hello and welcome to C++ Weekly. I'm your host, Jason Turner. In this episode
I just can't completely leave the topic of deducing 'this' without showing you
one of the most interesting things to me that it allows, and that has to do with lambdas.
Okay, so I've done other episodes on recursive lambdas. They don't work well,
but C++23's deducing 'this' kind of gives us a backdoor way of creating recursive lambda.
This is a very naive way of creating a factorial function defined recursively,
and you'll see this doesn't compile. I have no way of naming factorial inside a factorial. This
is just not something that lambdas allow for, but if we combine C++20's explicit template
parameters for lambdas with C++23's deducing 'this' then we should be able to get there.
So there we have it. I have created a template lambda that takes an implicit reference to itself
and the value that I want to iterate on. I pass in 4; and I should get 4 - comes in here, and
4 is not equal to 1 yet, so I return 4x the value of calling myself with 3, so that should be 4 x 3
x 2 x 1; and at 1 I break out, come back up the call stack. That should be 24 returned from 'main'
and, well, we see that the compiler didn't see through all of that and it is actually going to
do the recursive function call. So the compiler might need a little bit of work here before it
optimizes this all the way, but we can see that it is executing; and if we actually
execute the binary we can see 24 returned from 'main'. So yeah, there you have it. C++23's
deducing 'this' combined with C++20's explicit template parameters for lambdas will get us there.
And I just realized that I completely over complicated this example and really
could have just used an 'auto' parameter for self. So all of you who already are familiar
with deducing 'this' and this technique were probably yelling for the entirety of the episode,
but I did catch my mistake before finishing the recording. So both of these are possible,
and hopefully you enjoyed this episode of C++ Weekly. You know what to do.