Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do <: and :> mean when declaring a lambda? [duplicate]

I have stumbled across following lambda syntax, which I do not understand:

#include <iostream>

template<typename Callback>
void do_it(Callback callback) {
        callback();
}

template<typename T>
void p() {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main() {
        auto a = <:&:> { };
        p<decltype(a)>();
        do_it(<:&:> { std::cout << "Hello" << std::endl; }); //this
}

Program above produces an output:

void p() [with T = main()::__lambda0]
Hello

Could you explain, what does <:&:> {/* ... */} mean? Is it possible to declare this way a lambda which takes an argument?

like image 803
aadam Avatar asked May 19 '16 09:05

aadam


People also ask

How do you duplicate Lambda?

There is no provided function to copy/clone Lambda Functions and API Gateway configurations. You will need to create new a new function from scratch. If you envision having to duplicate functions in the future, it may be worthwhile to use AWS CloudFormation to create your Lambda Functions.

What does [&] mean in Lambda in C++?

It's a lambda capture list and has been defined in C++ from the C++11 standard. [&] It means that you're wanting to access every variable by reference currently in scope within the lambda function.

How do you declare a Lambda in C++?

A lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.

What is Idempotent Lambda?

Applied to Lambda, a function is idempotent when it can be invoked multiple times with the same event with no risk of side effects. To make a function idempotent, it must first identify that an event has already been processed. Therefore, it must extract a unique identifier, called an “idempotency key”.


1 Answers

<: and :> are digraphs. They get translated to [ and ] respectively. As such, your code is equivalent to:

auto a = [&] { };
do_it([&] { std::cout << "Hello" << std::endl; }); 

So it's just a lambda which captures everything by reference.

To declare a lambda which takes an argument like this, just add a parameter list after the capture group:

auto a = <:&:> (AType) { };

If you want whoever reads your code to hate you, you can use a mix of digraphs and trigraphs wherever possible:

auto a = <:&??)??<%>;
//       ^ same as [&]{}
like image 70
TartanLlama Avatar answered Oct 15 '22 05:10

TartanLlama