C++ 函式庫 - 運算子 Bool



描述

它用於檢查是否包含有效的目標。

宣告

以下是 std::function::function::operator bool 的宣告。

explicit operator bool() const;

C++11

explicit operator bool() const;

引數

返回值

如果 *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!
functional.htm
廣告