Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaration of lambdas in C++

In C++, it is possible to separate the declaration and definition of functions. For example, it is quite normal to declare a function:

int Foo(int x); 

in Foo.h and implement it in Foo.cpp. Is it possible to do something similar with lambdas? For example, define a

std::function<int(int)> bar; 

in bar.h and implement it in bar.cpp as:

std::function<int(int)> bar = [](int n) {     if (n >= 5)          return n;     return n*(n + 1); }; 

Disclaimer: I have experience with lambdas in C#, but I have not used them in C++ very much.

like image 782
MxNx Avatar asked Nov 22 '16 06:11

MxNx


People also ask

What is forward declaration in C?

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.

What is forward declaration of a function?

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.

What is lambda declaration?

You use a lambda expression to create an anonymous function. Use the lambda declaration operator => to separate the lambda's parameter list from its body. A lambda expression can be of any of the following two forms: Expression lambda that has an expression as its body: C# Copy.

Can lambdas be Inlined?

Calls of the lambda are translated to direct calls to its operator() and can therefore be inlined.


1 Answers

You can't separate declaration and definition of lambdas, neither forward declare it. Its type is a unique unnamed closure type which is declared with the lambda expression. But you could do that with std::function objects, which is designed to be able to store any callable target, including lambdas.

As your sample code shown you've been using std::function, just note that for this case bar is a global variable indeed, and you need to use extern in header file to make it a declaration (not a definition).

// bar.h extern std::function<int(int)> bar;     // declaration 

and

// bar.cpp std::function<int(int)> bar = [](int n) // definition {     if (n >= 5) return n;     return n*(n + 1); }; 

Note again that this is not separate declaration and definition of lambda; It's just separate declaration and definition of a global variable bar with type std::function<int(int)>, which is initialized from a lambda expression.

like image 149
songyuanyao Avatar answered Oct 03 '22 21:10

songyuanyao