我想知道如何正确检查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-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 callablehttps://stackoverflow.com/questions/21806632
复制相似问题