Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda-Over-Lambda in C++14

Tags:

c++

lambda

c++14

How following recursive lambda call ends/terminates ?

#include <cstdio>  auto terminal = [](auto term)            // <---------+   {                                        //           |     return [=] (auto func)               //           |  ???     {                                    //           |         return terminal(func(term));     // >---------+     }; };   auto main() -> int {     auto hello =[](auto s){ fprintf(s,"Hello\n"); return s; };     auto world =[](auto s){ fprintf(s,"World\n"); return s; };       terminal(stdout)             (hello)             (world) ;      return 0;  } 

What am I missing over here ?

Running code

like image 411
P0W Avatar asked Sep 02 '14 08:09

P0W


People also ask

Can lambda be Constexpr?

Visual Studio 2017 version 15.3 and later (available in /std:c++17 mode and later): A lambda expression may be declared as constexpr or used in a constant expression when the initialization of each data member that it captures or introduces is allowed within a constant expression.

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.

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

What is generic lambda in C++?

Generic lambdas were introduced in C++14 . Simply, the closure type defined by the lambda expression will have a templated call operator rather than the regular, non-template call operator of C++11 's lambdas (of course, when auto appears at least once in the parameter list).


1 Answers

It's not a recursive function call, look at it step-by-step:

  1. terminal(stdout) - this simply returns a lambda which has captured stdout
  2. The result of 1. is called with the lambda hello, which executes the lambda (func(term)), the result of which is passed to terminal(), which simply returns a lambda as in 1.
  3. The result of 2. is called with the lambda world, which does the same as 2, this time the return value is discarded...
like image 66
Nim Avatar answered Sep 27 '22 18:09

Nim