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?
mutable
, exception specifications, attributes, and captures. I could see skipping over some of those when first teaching lambdas, but not the return type.