且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何正确检查std :: function在C ++ 11中是否为空?

更新时间:2023-11-25 23:44:22

您不是要检查空的lambda,而是 std :: function 有一个可调用的目标存储在其中。由于 std :: function ::,检查是明确定义的并且有效运算符bool 允许在需要布尔值的上下文中(例如 bool c $ c> if 语句。)

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

此外,空lambda 的概念并没有真正使感。在后台,编译器将lambda表达式转换为 struct (或 class )定义,并将捕获的变量存储作为此结构的数据成员。还定义了一个公共函数调用运算符,它使您可以调用lambda。那么空的lambda是什么呢?

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?

您还可以编写 if(eventFunc!= nullptr )(如果需要),它等同于问题中的代码。 std :: function 定义 operator == operator!= 重载以与 nullptr_t $ c $进行比较c>。

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.