Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do define anonymous functions in C++?

Can I define functions in C++ inline? I am not talking about lambda functions, not the inline keyword that causes a compiler optimization.

like image 753
danijar Avatar asked Sep 18 '12 19:09

danijar


People also ask

How do you define an anonymous function?

An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.

Are there anonymous functions in C?

C (non-standard extension)The anonymous function is not supported by standard C programming language, but supported by some C dialects, such as GCC and Clang.

What is anonymous function explain with example?

In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.

Can we assign an anonymous function?

An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.


2 Answers

C++11 added lambda functions to the language. The previous versions of the language (C++98 and C++03), as well as all current versions of the C language (C89, C99, and C11) do not support this feature. The syntax looks like:

[capture](parameters)->return-type{body} 

For example, to compute the sum of all of the elements in a vector:

std::vector<int> some_list; int total = 0; for (int i=0;i<5;i++) some_list.push_back(i); std::for_each(begin(some_list), end(some_list), [&total](int x) {   total += x; }); 
like image 65
Adam Rosenfield Avatar answered Oct 03 '22 23:10

Adam Rosenfield


In C++11, you can use closures:

void foo() {    auto f = [](int a, int b) -> int { return a + b; };     auto n = f(1, 2); } 

Prior to that, you can use local classes:

void bar() {    struct LocalClass    {        int operator()(int a, int b) const { return a + b; }    } f;     int n = f(1, 2); } 

Both versions can be made to refer to ambient variables: In the local class, you can add a reference member and bind it in the constructor; and for the closure you can add a capture list to the lambda expression.

like image 23
Kerrek SB Avatar answered Oct 03 '22 22:10

Kerrek SB