Can I force a C++11 lambda to return by reference?

2019-04-03 09:26发布

问题:

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;
}

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

回答1:

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++ c++11 lambda