]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
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 | ||
8 | [section:explicit_operator_bool explicit_operator_bool] | |
9 | ||
10 | [/=================] | |
11 | [simplesect Authors] | |
12 | [/=================] | |
13 | ||
14 | * Andrey Semashev | |
15 | ||
16 | [endsimplesect] | |
17 | ||
18 | [/===============] | |
19 | [section Overview] | |
20 | [/===============] | |
21 | ||
22 | Header `<boost/core/explicit_operator_bool.hpp>` provides | |
23 | `BOOST_EXPLICIT_OPERATOR_BOOL()`, `BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT()` | |
24 | and `BOOST_CONSTEXPR_EXPLICIT_OPERATOR_BOOL()` compatibility helper macros | |
25 | that expand to an explicit conversion operator to `bool`. For compilers not | |
26 | supporting explicit conversion operators introduced in C++11 the macros expand | |
27 | to a conversion operator that implements the | |
28 | [@http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool safe bool idiom]. | |
29 | In case if the compiler is not able to handle safe bool idiom well the macros | |
30 | expand to a regular conversion operator to `bool`. | |
31 | ||
32 | [endsect] | |
33 | ||
34 | [/===============] | |
35 | [section Examples] | |
36 | [/===============] | |
37 | ||
38 | Both macros are intended to be placed within a user's class definition. The | |
39 | generated conversion operators will be implemented in terms of `operator!()` | |
40 | that should be defined by user in this class. In case of | |
41 | `BOOST_CONSTEXPR_EXPLICIT_OPERATOR_BOOL()` the generated conversion operator | |
42 | will be declared `constexpr` which requires the corresponding `operator!()` | |
43 | to also be `constexpr`. | |
44 | ||
45 | `` | |
46 | template< typename T > | |
47 | class my_ptr | |
48 | { | |
49 | T* m_p; | |
50 | ||
51 | public: | |
52 | BOOST_EXPLICIT_OPERATOR_BOOL() | |
53 | ||
54 | bool operator!() const | |
55 | { | |
56 | return !m_p; | |
57 | } | |
58 | }; | |
59 | `` | |
60 | ||
61 | Now `my_ptr` can be used in conditional expressions, similarly to a regular pointer: | |
62 | ||
63 | `` | |
64 | my_ptr< int > p; | |
65 | if (p) | |
66 | std::cout << "true" << std::endl; | |
67 | `` | |
68 | ||
69 | [endsect] | |
70 | ||
71 | [/==============] | |
72 | [section History] | |
73 | [/==============] | |
74 | ||
75 | [heading boost 1.56] | |
76 | ||
77 | * Added new macros `BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT` and `BOOST_CONSTEXPR_EXPLICIT_OPERATOR_BOOL` to define `noexcept` and `constexpr` operators. | |
78 | * The header moved to Boost.Core. | |
79 | ||
80 | [heading boost 1.55] | |
81 | ||
82 | * The macro was extracted from Boost.Log. | |
83 | ||
84 | [endsect] | |
85 | ||
86 | [endsect] |