Created
February 28, 2025 05:03
-
-
Save ParadoxV5/c2aa48fe88b30166930b29eaec5b383a to your computer and use it in GitHub Desktop.
Yes, there are null lambdas in C++!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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