Skip to content

Commit 1549905

Browse files
authored
[spec] Improve opCast & opCast!bool docs (#3652)
* [spec] Improve opCast docs Add runnable example. Clarify wording for implicit cast to bool. This does not happen whenever a bool is expected. * Part of Issue 18998 - Improve Operator Overloading docs * Use 'boolean conditional expressions' to include loops & static tests * Mention implicit conversion to cast type
1 parent d5038c3 commit 1549905

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

spec/operatoroverloading.dd

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -240,12 +240,31 @@ $(H2 $(LEGACY_LNAME2 Cast, cast, Cast Operator Overloading))
240240
expression, except in the case of boolean operations (see next
241241
section).)
242242

243+
$(SPEC_RUNNABLE_EXAMPLE_RUN
244+
---
245+
struct S
246+
{
247+
void* mem;
248+
249+
bool opCast(T)()
250+
if (is(T == bool)) => mem !is null;
251+
}
252+
253+
S s = S(new int);
254+
auto b = cast(bool) s;
255+
assert(b);
256+
//b = s; // error
257+
---
258+
)
259+
$(P If the return type of `opCast` differs from the *type* parameter of
260+
the `cast`, then the result is implicitly converted to *type*.)
261+
243262
$(H3 $(LNAME2 boolean_operators, Boolean Operations))
244263

245-
$(P Notably absent from the list of overloaded unary operators is the !
264+
$(P Notably absent from the list of overloaded unary operators is the `!`
246265
logical negation operator. More obscurely absent is a unary operator
247-
to convert to a bool result.
248-
Instead, these are covered by a rewrite to:
266+
to convert to a `bool` result.
267+
Instead, for structs these are covered by a rewrite to:
249268
)
250269
---
251270
opCast!(bool)(e)
@@ -258,11 +277,16 @@ if (e) => if (e.opCast!(bool))
258277
if (!e) => if (!e.opCast!(bool))
259278
---
260279

261-
$(P etc., whenever a bool result is expected. This only happens, however, for
262-
instances of structs. Class references are converted to bool by checking to
280+
$(P and similarly for other boolean conditional expressions and
281+
$(DDSUBLINK spec/expression, logical_expressions, logical operators) used
282+
on the struct instance.)
283+
284+
$(P This only happens, however, for
285+
instances of structs. Class references are converted to `bool` by checking to
263286
see if the class reference is null or not.
264287
)
265288

289+
266290
$(H2 $(LEGACY_LNAME2 Binary, binary, Binary Operator Overloading))
267291

268292
$(P The following binary operators are overloadable:)

0 commit comments

Comments
 (0)