从函数返回lambda表达式的返回值有什么意义? [英] What is the significance of returning the return value of a lambda expression from a function?

查看:165
本文介绍了从函数返回lambda表达式的返回值有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自C ++ 17起可以使用 constexpr 函数中的lambda表达式。

Since C++17 it is possible to use a lambda expression in a constexpr function.

在相关文档中 用于constexpr lambda的文字 显示此代码示例:

In the related document Wording for constexpr lambda this code example is shown:


constexpr int AddEleven(int n) {
    return [n] { return n + 11; }();
}


这只是一个玩具示例,用于演示语言功能,还是在实际使用情况下,此代码的行为与以下代码不同?

Is this just a toy example to demonstrate the language feature, or is there an actual use case where this code has a different behaviour than the following code?

constexpr int AddEleven(int n) {
    return n + 11;
}

在这种情况下使用lambda表达式有什么好处?

What would be the benefit of using a lambda expression in this case?

推荐答案

立即调用的lambda可用于在表达式中提供声明友好的范围,通常用于初始化 const 变量以比构造函数参数允许的更复杂的方式:

Immediately-invoked lambdas are useful to provide a statement-friendly scope within an expression, typically to initialize const variables in a more complex way than constructor parameters permit:

auto const v = [&] {
    std::vector<int> v;

    // do some stuff
    for(/*...*/)
        v.push_back(/*...*/);

    return v;
}();

return 语句必须已经出现在范围中,因此将其与上述模式结合起来并没有太大的好处。但是,我可以想象它曾经用来澄清需要初始化的早期条件:

A return statement must already appears in a scope, so there's not a huge benefit to combining it with the above pattern. I could, however imagine it used to clarify an early-out condition which requires such an initialization:

if(/* some corner case */)
    return [&] {
        std::vector<int> v;
    
        // do some stuff
        for(/*...*/)
            v.push_back(/*...*/);
    
        return v;
    }();

...相比:

if(/* some corner case */) {
    std::vector<int> v;
    
    // do some stuff
    for(/*...*/)
        v.push_back(/*...*/);
    
    return v;
}

...其中 return 是远离疾病。

... where the return is further away from the condition.

这篇关于从函数返回lambda表达式的返回值有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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