Forward declaration of lambdas in C++

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


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

Leave a Comment