Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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

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

like image 908
Martin Drozdik Avatar asked May 28 '13 10:05

Martin Drozdik


People also ask

Can you return a lambda function?

The lambda function can take many arguments but can return only one expression.

What is the correct syntax for lambda expression in C++11?

Lambdas can both capture variables and accept input parameters. A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; };

Can lambda expression have return type?

A return statement is not an expression in a lambda expression. We must enclose statements in braces ({}). However, we do not have to enclose a void method invocation in braces. The return type of a method in which lambda expression used in a return statement must be a functional interface.

How do you pass a lambda function in C++?

Permalink. All the alternatives to passing a lambda by value actually capture a lambda's address, be it by const l-value reference, by non-const l-value reference, by universal reference, or by pointer.


1 Answers

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; } 
like image 180
Mike Vine Avatar answered Sep 22 '22 13:09

Mike Vine