C++ Functional 库 - Operator Bool
描述
它用于检查是否包含有效目标。
声明
以下是 std::function::function::operator bool 的声明。
explicit operator bool() const;
C++11
explicit operator bool() const;
参数
none
返回值
如果 *this 存储了一个可调用函数目标,则返回 true,否则返回 false。
异常
noexcept:不抛出任何异常。
示例
在下面的 std::function::operator bool 示例中。
#include <functional>
#include <iostream>
void sampleFunction() {
std::cout << "This is the sample example of function!\n";
}
void checkFunc( std::function<void()> &func ) {
if( func ) {
std::cout << "Function is not empty! It is a calling function.\n";
func();
} else {
std::cout << "Function is empty.\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. f2: Function is not empty! It is a calling function. This is the sample example of function!

