The standard mentions places where a value may be “contextually converted to bool
“. They fall into four main groups:
Statements
-
if (t) /* statement */;
-
for (;t;) /* statement */;
-
while (t) /* statement */;
-
do { /* block */ } while (t);
Expressions
-
!t
-
t && t2
-
t || t2
-
t ? "true" : "false"
Compile-time tests
-
static_assert(t);
-
noexcept(t)
-
explicit(t)
-
if constexpr (t)
The conversion operator needs to be constexpr
for these.
Algorithms and concepts
-
NullablePointer T
Anywhere the Standard requires a type satisfying this concept (e.g. the
pointer
type of astd::unique_ptr
), it may be contextually converted. Also, the return value of aNullablePointer
‘s equality and inequality operators must be contextually convertible tobool
. -
std::remove_if(first, last, [&](auto){ return t; });
In any algorithm with a template parameter called
Predicate
orBinaryPredicate
, the predicate argument can return aT
. -
std::sort(first, last, [&](auto){ return t; });
In any algorithm with a template parameter called
Compare
, the comparator argument can return aT
.
(source1, source2)
Do be aware that a mix of const and non-const conversion operators can cause confusion:
- Why doesn’t explicit bool() conversion happen in contextual conversion?
- Why does the
explicit operator bool
not in effect as expected?