explicit_operator_bool.qbk 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. [/
  2. / Copyright (c) 2013 Andrey Semashev
  3. /
  4. / Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. /]
  7. [section:explicit_operator_bool explicit_operator_bool]
  8. [/=================]
  9. [simplesect Authors]
  10. [/=================]
  11. * Andrey Semashev
  12. [endsimplesect]
  13. [/===============]
  14. [section Overview]
  15. [/===============]
  16. Header `<boost/core/explicit_operator_bool.hpp>` provides
  17. `BOOST_EXPLICIT_OPERATOR_BOOL()`, `BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT()`
  18. and `BOOST_CONSTEXPR_EXPLICIT_OPERATOR_BOOL()` compatibility helper macros
  19. that expand to an explicit conversion operator to `bool`. For compilers not
  20. supporting explicit conversion operators introduced in C++11 the macros expand
  21. to a conversion operator that implements the
  22. [@http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool safe bool idiom].
  23. In case if the compiler is not able to handle safe bool idiom well the macros
  24. expand to a regular conversion operator to `bool`.
  25. [endsect]
  26. [/===============]
  27. [section Examples]
  28. [/===============]
  29. Both macros are intended to be placed within a user's class definition. The
  30. generated conversion operators will be implemented in terms of `operator!()`
  31. that should be defined by user in this class. In case of
  32. `BOOST_CONSTEXPR_EXPLICIT_OPERATOR_BOOL()` the generated conversion operator
  33. will be declared `constexpr` which requires the corresponding `operator!()`
  34. to also be `constexpr`.
  35. ``
  36. template< typename T >
  37. class my_ptr
  38. {
  39. T* m_p;
  40. public:
  41. BOOST_EXPLICIT_OPERATOR_BOOL()
  42. bool operator!() const
  43. {
  44. return !m_p;
  45. }
  46. };
  47. ``
  48. Now `my_ptr` can be used in conditional expressions, similarly to a regular pointer:
  49. ``
  50. my_ptr< int > p;
  51. if (p)
  52. std::cout << "true" << std::endl;
  53. ``
  54. [endsect]
  55. [/==============]
  56. [section History]
  57. [/==============]
  58. [heading boost 1.56]
  59. * Added new macros `BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT` and `BOOST_CONSTEXPR_EXPLICIT_OPERATOR_BOOL` to define `noexcept` and `constexpr` operators.
  60. * The header moved to Boost.Core.
  61. [heading boost 1.55]
  62. * The macro was extracted from Boost.Log.
  63. [endsect]
  64. [endsect]