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.
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.