Skip to content

Commit 413afd4

Browse files
authored
Merge pull request #2146 from RazvanN7/patch-5
Update docs to highlight lambda comparison
2 parents 45ee86e + deae0dc commit 413afd4

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

spec/traits.dd

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,6 +1008,68 @@ void main()
10081008
$(P If the two arguments are expressions made up of literals
10091009
or enums that evaluate to the same value, true is returned.)
10101010

1011+
$(P If the two arguments are both lambda functions (or aliases
1012+
to lambda functions), then they are compared for equality. For
1013+
the comparison to be computed correctly, the following conditions
1014+
must be met for both lambda functions:)
1015+
1016+
$(OL
1017+
$(LI The lambda function arguments must not have a template
1018+
instantiation as an explicit argument type. Any other argument
1019+
types (basic, user-defined, template) are supported.)
1020+
$(LI The lambda function body must contain a single expression
1021+
(no return statement) which contains only numeric values,
1022+
manifest constants, enum values and function arguments. If the
1023+
expression contains local variables, function calls or return
1024+
statements, the function is considered uncomparable.)
1025+
)
1026+
1027+
$(P If these constraints aren't fulfilled, the function is considered
1028+
incomparable and `isSame` returns $(D false).)
1029+
1030+
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
1031+
---
1032+
void main()
1033+
{
1034+
static assert(__traits(isSame, (a, b) => a + b, (c, d) => c + d));
1035+
static assert(__traits(isSame, a => ++a, b => ++b));
1036+
static assert(!__traits(isSame, (int a, int b) => a + b, (a, b) => a + b));
1037+
static assert(__traits(isSame, (a, b) => a + b + 10, (c, d) => c + d + 10));
1038+
1039+
// lambdas accessing local variables are considered incomparable
1040+
int b;
1041+
static assert(!__traits(isSame, a => a + b, a => a + b));
1042+
1043+
// lambdas calling a function inside their body are considered incomparable
1044+
int f() { return 3;}
1045+
static assert(!__traits(isSame, a => a + f(), a => a + f()));
1046+
1047+
class A
1048+
{
1049+
int a;
1050+
this(int a)
1051+
{
1052+
this.a = a;
1053+
}
1054+
}
1055+
1056+
class B
1057+
{
1058+
int a;
1059+
this(int a)
1060+
{
1061+
this.a = a;
1062+
}
1063+
}
1064+
1065+
static assert(__traits(isSame, (A a) => ++a.a, (A b) => ++b.a));
1066+
// lambdas with different data types are considered incomparable,
1067+
// even if the memory layout is the same
1068+
static assert(!__traits(isSame, (A a) => ++a.a, (B a) => ++a.a));
1069+
}
1070+
---
1071+
)
1072+
10111073
$(H2 $(GNAME compiles))
10121074

10131075
$(P Returns a bool $(D true) if all of the arguments

0 commit comments

Comments
 (0)