o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
c++ lambda 引用函數自身
- User
c++ lambda 引用函數自身
- Assistant
c++ lambda 引用函數自身
在C++中,Lambda 表达式默认是匿名且无法直接引用自身,这使得实现递归变得有些棘手。不过,通过使用一些技巧,仍然可以让 Lambda 自我引用,从而实现递归功能。以下是几种常见的方法:
std::function 包装 Lambda这是最经典的方法,适用于 C++11 及以上版本。通过将 Lambda 赋值给 std::function,然后在 Lambda 内部通过捕获引用来实现递归。
#include <iostream>
#include <functional>
int main() {
// 定义一个 std::function 用于存储 Lambda
std::function<int(int)> factorial = [&](int n) -> int {
if (n <= 1)
return 1;
return n * factorial(n - 1); // 通过 std::function 实现递归
};
int number = 5;
std::cout << "Factorial of " << number << " is " << factorial(number) << std::endl;
return 0;
}
输出:
Factorial of 5 is 120
Y Combinator 是一种函数式编程中的技巧,可以在不使用 std::function 的情况下实现递归。这种方法在某些情况下性能更优,因为避免了 std::function 的开销。
#include <iostream>
#include <utility>
template <typename F>
struct y_combinator_result {
F f;
y_combinator_result(F&& f_) : f(std::forward<F>(f_)) {}
template <typename... Args>
decltype(auto) operator()(Args&&... args) {
return f(*this, std::forward<Args>(args)...);
}
};
template <typename F>
auto y_combinator(F&& f) {
return y_combinator_result<F>(std::forward<F>(f));
}
int main() {
auto factorial = y_combinator([](auto self, int n) -> int {
if (n <= 1)
return 1;
return n * self(n - 1);
});
int number = 5;
std::cout << "Factorial of " << number << " is " << factorial(number) << std::endl;
return 0;
}
输出:
Factorial of 5 is 120
auto 捕获自身(C++20)在 C++20 中,可以利用 auto 捕获自身,从而使 Lambda 能够引用自身,实现递归。
#include <iostream>
int main() {
// 使用 auto 捕获自身
auto factorial = [&](auto& self, int n) -> int {
if (n <= 1)
return 1;
return n * self(self, n - 1);
};
int number = 5;
std::cout << "Factorial of " << number << " is " << factorial(factorial, number) << std::endl;
return 0;
}
输出:
Factorial of 5 is 120
这种方法通过让 Lambda 捕获自身的引用来实现递归。不过,需要注意捕获顺序,以确保 Lambda 能够正确引用自身。
#include <iostream>
#include <functional>
int main() {
// 先定义一个 std::function,再定义 Lambda 并赋值
std::function<int(int)> factorial = [&](int n) -> int {
if (n <= 1)
return 1;
return n * factorial(n - 1);
};
int number = 5;
std::cout << "Factorial of " << number << " is " << factorial(number) << std::endl;
return 0;
}
输出:
Factorial of 5 is 120
尽管 Lambda 表达式本身不支持直接递归,但通过使用 std::function 包装、Y Combinator 模式或 C++20 中的高级特性,可以实现 Lambda 的递归调用。选择哪种方法取决于具体的需求和使用的 C++ 标准版本。