首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确检查C++11中std::function是否为空?

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

Stack Overflow用户
提问于 2014-02-16 10:44:01
回答 3查看 77.1K关注 0票数 117

我想知道如何正确检查std::function是否为空。考虑这个例子:

代码语言:javascript
复制
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语句解决了这个问题:

代码语言:javascript
复制
   void doSomething() {
        ...
        if (eventFunc) {
            eventFunc(42);
        }
   }

这是可行的,但我仍然想知道未初始化的std::function的值是什么?我想写if (eventFunc != nullptr),但是std::function (显然)不是一个指针。

为什么纯if有效呢?它背后的魔力是什么?而且,这是正确的方式如何检查它?

EN

Stack Overflow用户

发布于 2014-06-25 17:07:17

请在此处查看std::function::operator bool

返回值

如果对象为callable.

  • false,则为
  • ;否则为true(对象为空函数)。

示例 Play with it online

代码语言:javascript
复制
// 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
}

输出

代码语言:javascript
复制
[1] foo is EMPTY
[2] foo is NOT empty
[3] foo is callable
[4] foo is NOT callable
[5] foo is callable
票数 30
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21806632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档