int main() {
auto fn = []<typename T>(this auto&& self, T n) {
if (n > 0) {
self(n - 1);
}
};
fn(3);
}
Compiled with clang-20 -std=c++23 but got the following errors:
<source>:4:13: error: function 'operator()<int, (lambda at <source>:2:15) &>' with deduced return type cannot be used before it is defined
4 | self(n - 1);
| ^
<source>:8:7: note: in instantiation of function template specialization 'main()::(anonymous class)::operator()<int, (lambda at <source>:2:15) &>' requested here
8 | fn(3);
| ^
<source>:2:15: note: 'operator()<int, (lambda at <source>:2:15) &>' declared here
2 | auto fn = []<typename T>(this auto&& self, T n) {
| ^
1 error generated.
Compiler returned: 1
see https://godbolt.org/z/PYbM8W9rv
Why does a recursive lambda with template parameters and the deducing(this) argument not work?
Your code snippet can be reduced to this:
auto fn (int x) { if (x > 0) fn (x - 1); }
And with some of the clutter cleared away, we can see that you are calling fn before the declaration of fn is complete. At the point you call fn the return type is not known, so the compiler is in a quandry. As pointed out in the comments, adding a (trailing) return type fixes it.
Godbolt:
https://godbolt.org/z/f1ExMvoM3
https://godbolt.org/z/fqhfjKcn8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With