C++ Functional Library - Operator Bool



Description

It is used to check if a valid target is contained.

Declaration

Following is the declaration for std::function::function::operator bool.

explicit operator bool() const;

C++11

explicit operator bool() const;

Parameters

none

Return Value

It returns true if *this stores a callable function target, false otherwise.

Exceptions

noexcept: It doesnot throw any exceptions.

Example

In below example for 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 );
}

The output should be like this −

f1: Function is empty.
f2: Function is not empty! It is a calling function.
This is the sample example of function!
functional.htm
Advertisements