我可以强制C ++ 11 lambda通过引用返回吗? [英] Can I force a C++11 lambda to return by reference?

查看:59
本文介绍了我可以强制C ++ 11 lambda通过引用返回吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 lambda 表达式按值返回,因此无法编译:

This does not compile since the lambda expression returns by value:

#include <iostream>

class Item
{
public:
    int& f(){return data_;}
private:
    int data_ = 0;
};

int main()
{
    Item item;
    auto lambda = [](Item& item){return item.f();};
    lambda(item) = 42;  // lambda(item) is a rvalue => compile time error 
    std::cout << item.f() << std::endl;
    return 0;
}

有没有办法解决?我可以强制Lambda通过引用返回 吗?

Is there a way around this? Can I force a lambda to return by reference?

推荐答案

您应将lambda返回类型指定为是 int& 。如果您不使用返回类型[并且lambda的格式为 return表达式; ,它将自动推断出返回类型。

You should specify the lambda return type to be int&. If you leave the return type off [and the lambda is of form return expression; it will automatically deduce the return type.

#include <iostream>

class Item
{
public:
    int& f(){return data_;}
private:
    int data_ = 0;
};

int main()
{
    Item item;
    auto lambda = [](Item& item) ->int& {return item.f();}; // Specify lambda return type
    lambda(item) = 42;
    std::cout << item.f() << std::endl;
    return 0;
}

这篇关于我可以强制C ++ 11 lambda通过引用返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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