C++ 参考手册

位置:首页 > C++ 参考手册 >工具库 >函数对象 >std::function > std::function<R(Args...)>::operator bool

explicit operator bool() const noexcept;
(C++11 起)

检查 *this 是否存储可调用函数对象,即非空。

参数

(无)

返回值

*this 存储可调用函数对象则为 true ,否则为 false

示例

#include <functional>
#include <iostream>
 
void sampleFunction()
{
    std::cout << "This is the sample function!\n";
}
 
void checkFunc( std::function<void()> &func )
{
    // 用 operator bool 确定可调用目标是否可用。
    if( func )  
    {
        std::cout << "Function is not empty! Calling function.\n";
        func();
    }
    else
    {
        std::cout << "Function is empty. Nothing to do.\n";
    }
}
 
int main()
{
    std::function<void()> f1;
    std::function<void()> f2( sampleFunction );
 
    std::cout << "f1: ";
    checkFunc( f1 );
 
    std::cout << "f2: ";
    checkFunc( f2 );
}

输出:

f1: Function is empty. Nothing to do.
f2: Function is not empty! Calling function.
This is the sample function!