Skip to content

Commit fc5885b

Browse files
committed
[operatoroverloading.dd] Add example for opBinary overloading
1 parent a47558e commit fc5885b

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

spec/operatoroverloading.dd

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,16 +254,43 @@ $(H2 $(LEGACY_LNAME2 Binary, binary, Binary Operator Overloading))
254254
---
255255
a $(METACODE op) b
256256
---
257-
$(P is rewritten as both:)
257+
$(P is rewritten as one of:)
258258
---
259259
a.opBinary!($(METACODE "op"))(b)
260260
b.opBinaryRight!($(METACODE "op"))(a)
261261
---
262262

263263
$(P and the one with the $(SINGLEQUOTE better) match is selected.
264-
It is an error for both to equally match.
264+
It is an error for both to equally match. Example:
265265
)
266266

267+
$(SPEC_RUNNABLE_EXAMPLE_RUN
268+
---
269+
struct S
270+
{
271+
int[] data;
272+
273+
// this ~ rhs
274+
int[] opBinary(string op : "~")(int rhs)
275+
{
276+
return data ~ rhs;
277+
}
278+
// lhs ~ this
279+
int[] opBinaryRight(string op : "~")(int lhs)
280+
{
281+
return lhs ~ data;
282+
}
283+
}
284+
285+
void main()
286+
{
287+
auto s = S([2,3]);
288+
assert(s ~ 4 == [2,3,4]); // opBinary
289+
assert(1 ~ s == [1,2,3]); // opBinaryRight
290+
}
291+
---
292+
)
293+
267294
$(P Operator overloading for a number of operators can be done at the same time.
268295
For example, if only the + or - operators are supported:)
269296

0 commit comments

Comments
 (0)