How Can I use Null Lambda in C++?

In this particular case, you can just define your null closure as one that always returns -1:

template <typename Lambda>
int foo(Lambda bar) {
    return bar(3);
}

#include <iostream>
int main() {
    auto const NULL_LAMBDA = [](int){ return -1; };
    std::cout << foo([](int a) {return a + 3;}) << std::endl;
    std::cout << foo(NULL_LAMBDA) << std::endl;
}

The likelihood is that if you're selecting at run-time which implementation to pass, then you're much better off type-erasing it with std::function rather than instantiating templates. And a std::function is permitted to be empty - it can be assigned from and compared against a null pointer.


If you know at compilation time that some call sites will always pass the 'null' lambda, then you can specialise the implementation appropriately. Obvious options include overloading foo() with a version that doesn't take the bar argument, or specializing it with a different implementation when bar is not a callable.

If much of foo() is common to both kinds of invocation (perhaps it has a lot of side effects, and bar() is provided as a callback?), then you might be able to conditionalise the optional part using std::is_same<>. This requires if constexpr, as the lambda is not callable as bar(3):

static auto const NULL_LAMBDA = nullptr;

#include <type_traits>
template <typename Lambda>
int foo(Lambda bar) {
    if constexpr (std::is_same<decltype(bar), std::nullptr_t>::value)
        return -1;
    else
        return bar(3);
}

#include <iostream>
int main() {
    std::cout << foo([](int a) {return a + 3;}) << std::endl;
    std::cout << foo(NULL_LAMBDA) << std::endl;
}

You can add a dedicated specialization:

#include <iostream>
#include <cstddef>

template<typename Lambda> int
foo(Lambda bar)
{
    return(bar(3));
}

template<> int
foo<::std::nullptr_t>(::std::nullptr_t)
{
    return(-1);
}

int main()
{
    ::std::cout << foo([] (int a) -> int {return(a + 3);}) << ::std::endl;
    ::std::cout << foo(nullptr) << ::std::endl;
}

Tags:

C++

Lambda

C++11