如何用C++编写漂亮的内联递归lambda?

问题描述 投票:0回答:1

据我所知,在 C++ 17 中,我可以像这样编写递归 lambda:

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

dfs(dfs, 0);

不幸的是,我不得不忍受多一个参数,这有点难看。我怀疑编译器是否有可能将其内联。新的 C++ 标准中有新的选项吗? (C++20 或 C++23)

c++ c++17 c++20
1个回答
1
投票

您可以将显式对象参数与推导类型一起使用:

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

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

这是 C++23 功能

© www.soinside.com 2019 - 2024. All rights reserved.