Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/utility/functional/function/operator bool"

From cppreference.com
< cpp‎ | utility‎ | functional‎ | function
m (r2.7.3) (Robot: Adding de, es, fr, it, ja, pt, ru, zh)
(added example)
Line 15: Line 15:
 
===Exceptions===
 
===Exceptions===
 
{{noexcept}}
 
{{noexcept}}
 +
 +
===Example===
 +
{{example
 +
| code=
 +
#include <functional>
 +
#include <iostream>
 +
 +
typedef std::function<void(int)> SomeVoidFunc;
 +
 +
class C
 +
{
 +
public:
 +
  C(SomeVoidFunc void_func = nullptr)
 +
  : void_func_(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
 +
}}
  
 
[[de:cpp/utility/functional/function/operator bool]]
 
[[de:cpp/utility/functional/function/operator bool]]

Revision as of 14:17, 22 January 2013

 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
 
Function objects
Function invocation
(C++17)(C++23)
Identity function object
(C++20)
Transparent operator wrappers
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

Old binders and adaptors
(until C++17*)
(until C++17*)
(until C++17*)
(until C++17*)  
(until C++17*)
(until C++17*)(until C++17*)(until C++17*)(until C++17*)
(until C++20*)
(until C++20*)
(until C++17*)(until C++17*)
(until C++17*)(until C++17*)

(until C++17*)
(until C++17*)(until C++17*)(until C++17*)(until C++17*)
(until C++20*)
(until C++20*)
 
 
explicit operator bool() const;
(since C++11)

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

Contents

Parameters

(none)

Return value

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

Exceptions

noexcept specification:  
noexcept
  

Example

#include <functional>
#include <iostream>
 
typedef std::function<void(int)> SomeVoidFunc;
 
class C
{
public:
  C(SomeVoidFunc void_func = nullptr)
  : void_func_(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