Skip to content

Commit

Permalink
[spec] Improve opCast & opCast!bool docs (#3652)
Browse files Browse the repository at this point in the history
* [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
  • Loading branch information
ntrel authored Jul 10, 2023
1 parent d5038c3 commit 1549905
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions spec/operatoroverloading.dd
Original file line number Diff line number Diff line change
Expand Up @@ -240,12 +240,31 @@ $(H2 $(LEGACY_LNAME2 Cast, cast, Cast Operator Overloading))
expression, except in the case of boolean operations (see next
section).)

$(SPEC_RUNNABLE_EXAMPLE_RUN
---
struct S
{
void* mem;

bool opCast(T)()
if (is(T == bool)) => mem !is null;
}

S s = S(new int);
auto b = cast(bool) s;
assert(b);
//b = s; // error
---
)
$(P If the return type of `opCast` differs from the *type* parameter of
the `cast`, then the result is implicitly converted to *type*.)

$(H3 $(LNAME2 boolean_operators, Boolean Operations))

$(P Notably absent from the list of overloaded unary operators is the !
$(P Notably absent from the list of overloaded unary operators is the `!`
logical negation operator. More obscurely absent is a unary operator
to convert to a bool result.
Instead, these are covered by a rewrite to:
to convert to a `bool` result.
Instead, for structs these are covered by a rewrite to:
)
---
opCast!(bool)(e)
Expand All @@ -258,11 +277,16 @@ if (e) => if (e.opCast!(bool))
if (!e) => if (!e.opCast!(bool))
---

$(P etc., whenever a bool result is expected. This only happens, however, for
instances of structs. Class references are converted to bool by checking to
$(P and similarly for other boolean conditional expressions and
$(DDSUBLINK spec/expression, logical_expressions, logical operators) used
on the struct instance.)

$(P This only happens, however, for
instances of structs. Class references are converted to `bool` by checking to
see if the class reference is null or not.
)


$(H2 $(LEGACY_LNAME2 Binary, binary, Binary Operator Overloading))

$(P The following binary operators are overloadable:)
Expand Down

0 comments on commit 1549905

Please sign in to comment.