Skip to content

Instantly share code, notes, and snippets.

@ParadoxV5
Created February 28, 2025 05:03
Show Gist options
  • Save ParadoxV5/c2aa48fe88b30166930b29eaec5b383a to your computer and use it in GitHub Desktop.
Save ParadoxV5/c2aa48fe88b30166930b29eaec5b383a to your computer and use it in GitHub Desktop.
Yes, there are null lambdas in C++!
// Lambda is a type of *value*, and *values* can’t be null.
// But y’know what can? *References* to values.
#include <functional>
#include <stdio.h>
const auto lambda = [] () -> const char* {
return "Hello from lambda!";
};
void null_by_pointer(const decltype(lambda)* f) {
puts(f ? (*f)() : "*f is null dereference!");
}
/** https://en.cppreference.com/w/cpp/utility/functional/function/operator_bool */
void null_by_std_function(std::function<const char*()> f) {
puts(f ? f() : "f is empty!");
}
int main() {
null_by_pointer(&lambda);
null_by_pointer(nullptr);
null_by_std_function(lambda);
null_by_std_function(std::function<const char*()>()); // equivalent to std::function<…>(nullptr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment