Nig*_*fik 87 c++ c++11 std-function
我想知道如何正确检查是否std::function
为空.考虑这个例子:
class Test {
std::function<void(int a)> eventFunc;
void registerEvent(std::function<void(int a)> e) {
eventFunc = e;
}
void doSomething() {
...
eventFunc(42);
}
};
Run Code Online (Sandbox Code Playgroud)
这段代码在MSVC中编译得很好,但如果我在doSomething()
没有初始化的情况下调用eventFunc
代码,那么显然会崩溃.这是预期的,但我想知道它的价值是eventFunc
多少?调试器说'empty'
.所以我使用简单的if语句修复了它:
void doSomething() {
...
if (eventFunc) {
eventFunc(42);
}
}
Run Code Online (Sandbox Code Playgroud)
这有效,但我仍然想知道非初始化的价值是std::function
多少?我想写,if (eventFunc != nullptr)
但std::function
(显然)不是指针.
为什么纯净如果有效?它背后的魔力是什么?而且,这是检查它的正确方法吗?
Pra*_*ian 92
你没有检查一个空的lambda,但是它是否std::function
有一个可调用的目标.检查是明确定义的,因为std::function::operator bool
它允许bool
在需要布尔值的上下文中隐式转换(例如if
语句中的条件表达式).
此外,空lambda的概念并不真正有意义.在后台,编译器将lambda表达式转换为struct
(或class
)定义,并将捕获的变量存储为此数据的成员struct
.还定义了一个公共函数调用操作符,它允许您调用lambda.那么一个空的lambda会是什么?
if(eventFunc != nullptr)
如果你愿意,你也可以写,它等同于你在问题中的代码.std::function
定义 operator==
和operator!=
重载以与a进行比较nullptr_t
.
Daw*_*ozd 20
点击这里http://www.cplusplus.com/reference/functional/function/operator_bool/
例
// 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;
}
Run Code Online (Sandbox Code Playgroud)
产量
foo不可调用.
酒吧是可以赎回的.
(让我给出一个明确的答案。)
您可以使用 检查 a 是否std::function
为空std::function::operator bool
。
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;
}
Run Code Online (Sandbox Code Playgroud)
输出
foo 不为空。
酒吧是空的。