Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write an inline recursive lambda in C++?

Tags:

c++

c++20

c++23

As I know in C++17, I can write a recursive lambda like this:

auto dfs = [&](const auto &self, int x) -> void {
    // ....
    self(self, x);
};

dfs(dfs, 0);

Unfortunately, I have to endure one more parameter which is a bit ugly. And I doubt the possibility for the compiler to make it inline. Are there new options in new C++ standards? (C++20 or C++23)

like image 812
Junhui Zhu Avatar asked Nov 17 '25 02:11

Junhui Zhu


1 Answers

You can use an explicit object parameter with a deduced type:

auto dfs = [&](this const auto &self, int x) -> void {
    // ....
    self(x);
};

dfs(0);  // `self` is `dfs`

This is a C++23 feature

like image 140
Artyer Avatar answered Nov 18 '25 17:11

Artyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!