我想知道如何正确检查std::function是否为空。考虑这个例子:
class Test {
std::function<void(int a)> eventFunc;
void registerEvent(std::function<void(int a)> e) {
eventFunc = e;
}
void doSomething() {
...
eventFunc(42);
}
};这段代码在MSVC中编译得很好,但是如果我在没有初始化eventFunc的情况下调用doSomething(),代码显然会崩溃。这是意料之中的,但我想知道eventFunc的价值是什么?调试器显示为'empty'。所以我用简单的if语句解决了这个问题:
void doSomething() {
...
if (eventFunc) {
eventFunc(42);
}
}这是可行的,但我仍然想知道未初始化的std::function的值是什么?我想写if (eventFunc != nullptr),但是std::function (显然)不是一个指针。
为什么纯if有效呢?它背后的魔力是什么?而且,这是正确的方式如何检查它?
发布于 2014-02-16 10:56:10
您不是在检查一个空的lambda,而是检查std::function中是否存储了一个可调用的目标。检查是定义良好的,因为std::function::operator bool允许在需要布尔值的上下文(如if语句中的条件表达式)中隐式转换为bool。
此外,空lambda的概念并不真正有意义。在幕后,编译器将lambda表达式转换为struct (或class)定义,并将捕获的变量存储为该struct的数据成员。还定义了一个公共函数调用操作符,它允许您调用lambda。那么一个空的lambda会是什么呢?
如果您愿意,您也可以编写if(eventFunc != nullptr),它等同于您在问题中拥有的代码。std::function defines operator==和operator!=重载,用于与nullptr_t进行比较。
发布于 2014-06-25 17:07:17
请在此处查看std::function::operator bool
返回值
如果对象为callable.
// function::operator bool example
#include <iostream> // std::cout
#include <functional> // std::function, std::plus
int main ()
{
std::function<int(int,int)> foo; // empty
if(foo)
{
std::cout << "[1] foo is NOT empty" << std::endl;
}
else
{
std::cout << "[1] foo is EMPTY" << std::endl;
}
// Now we can assign example
foo = std::plus<int>();
if(foo)
{
std::cout << "[2] foo is NOT empty" << std::endl;
}
else
{
std::cout << "[2] foo is EMPTY" << std::endl;
}
// Example use with ternary operator (https://www.cprogramming.com/reference/operators/ternary-operator.html)
std::cout << "[3] foo is " << (foo ? "callable" : "NOT callable") << std::endl;
// make it empty
foo = {};
std::cout << "[4] foo is " << (foo ? "callable" : "NOT callable") << std::endl;
foo = [](int a, int b){ return a+b; };
std::cout << "[5] foo is " << (foo ? "callable" : "NOT callable") << std::endl;
return foo(1, 1) == 2; // return 1
}输出
[1] foo is EMPTY
[2] foo is NOT empty
[3] foo is callable
[4] foo is NOT callable
[5] foo is callable发布于 2019-11-20 16:32:15
(让我提供一个明确的答案。)
您可以使用std::function::operator bool检查std::function是否为空。
true:如果对象是可调用的。
false:否则(对象为空函数)
示例
#include <iostream>
#include <functional>
int main ()
{
std::function<int(int,int)> foo = std::plus<int>();//assigned: not empty
std::function<int(int,int)> bar;//not assigned: empty
std::cout << "foo is " << (foo ? "not empty" : "empty") << ".\n";
std::cout << "bar is " << (bar ? "not empty" : "empty") << ".\n";
return 0;
}输出
foo不为空。
条形图为空。
https://stackoverflow.com/questions/21806632
复制相似问题