How to properly check if std::function is empty in C++11?
You're not checking for an empty lambda, but whether the std::function
has a callable target stored in it. The check is well-defined and works because of std::function::operator bool
which allows for implicit conversion to bool
in contexts where boolean values are required (such as the conditional expression in an if
statement).
Besides, the notion of an empty lambda doesn't really make sense. Behind the scenes the compiler converts a lambda expression into a struct
(or class
) definition, with the variables you capture stored as data members of this struct
. A public function call operator is also defined, which is what allows you to invoke the lambda. So what would an empty lambda be?
You can also write if(eventFunc != nullptr)
if you wish to, it's equivalent to the code you have in the question. std::function
defines operator==
and operator!=
overloads for comparing with a nullptr_t
.
Check here http://www.cplusplus.com/reference/functional/function/operator_bool/
Example
// function::operator bool example
#include <iostream> // std::cout
#include <functional> // std::function, std::plus
int main () {
std::function<int(int,int)> foo,bar;
foo = std::plus<int>();
foo.swap(bar);
std::cout << "foo is " << (foo ? "callable" : "not callable") << ".\n";
std::cout << "bar is " << (bar ? "callable" : "not callable") << ".\n";
return 0;
}
Output
foo is not callable.
bar is callable.