std::function::operator bool

From cppreference.com
< cpp‎ | utility‎ | functional‎ | function
 
 
 
Function objects
Function wrappers
(C++11)
(C++11)
Bind
(C++11)
(C++11)
(C++11)
Reference wrappers
(C++11)(C++11)
Operator wrappers
Negators
Deprecated binders and adaptors
(deprecated)
(deprecated)
(deprecated)
(deprecated)
(deprecated)(deprecated)(deprecated)(deprecated)
(deprecated)
(deprecated)(deprecated)(deprecated)(deprecated)
(deprecated)(deprecated)
(deprecated)(deprecated)
 
 
explicit operator bool() const;
(since C++11)

Checks whether *this stores a callable function target, i.e. is not empty.

Contents

[edit] Parameters

(none)

[edit] Return value

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

[edit] Exceptions

noexcept specification:  
noexcept
  

[edit] Example

#include <functional>
#include <iostream>
 
typedef std::function<void(int)> SomeVoidFunc;
 
class C {
  public:
    C(SomeVoidFunc void_func = nullptr)
        : void_func_(std::move(void_func))
    {
        if (!void_func_) {
            void_func_ = std::bind(&C::default_func, this, std::placeholders::_1);
        }
        void_func_(7);
    }
 
    void default_func(int i) { std::cout << i << '\n'; };
 
  private:
    SomeVoidFunc void_func_;
};
 
void user_func(int i)
{
    std::cout << (i + 1) << '\n';
}
 
int main()
{
    C c1;
    C c2(user_func);
}

Output:

7
8