Mzhr Mzhr - 12 days ago 5
C++ Question

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

Answer

You can. Just note that for this case bar 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: This is not separate declaration and definition of labmda; 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.

Comments