在声明它的同一行中调用C ++递归lambda [英] Call C++ recursive lambda in the same line where it is declared

查看:68
本文介绍了在声明它的同一行中调用C ++递归lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这主要是一个线性格式的问题,出于可读性原因,我通常还是会以多行形式编写此代码。

This is mostly a one liner style type of question, I would normally write this code in multiple lines anyway for readability reasons.

所以我的问题是我可以打电话吗

So my question is can I call the recursive lambda in the same statement where it is defined?

因此而不是:

int n=3;
function<void(int)> f {[n,&f](int i){if (i>1) { cout << "func(a, "; f(i-1); cout << ")";} else cout << "a";}};
f(n);

在同一位置调用 n

推荐答案

让我瞥见人们通常使用组合器来处理递归lambda。有一个提案(P0200r0)去年在标准库中添加了一个简单的Y组合器。

Let me offer a glimpse into the functional programming world, where people usually use combinators to deal with recursive lambdas. There was a proposal (P0200r0) last year to add a simple Y-combinator to the standard library.

不考虑这样做是否是一个好主意,这将允许您编写和编写调用这样的递归lambda:

Leaving aside the question whether it is a good idea to do this, this would allow you to write and invoke a recursive lambda like this:

y_combinator([](auto self, int i){
    if (i>1) {
        std::cout << "func(a, ";
        self(i-1);
        std::cout << ")";
    } else {
        std::cout << "a";
    }
})(6);

这里的基本思想是y-combinator是一个高阶函数,它包装了一个lambda通过自己作为第一个论点。组合器负责为lambda的所有调用包装self参数。

The basic idea here is that the y-combinator is a higher order function that wraps a lambda which is passed 'itself' as a first argument. The combinator takes care of wrapping the self argument away for all invocations of the lambda.

您可以在coliru中试用

这篇关于在声明它的同一行中调用C ++递归lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆