On 2017-01-09 20:18, Ali Çehreli wrote:
This is something that surprised me in a friend's code.
(A "friend", hmmm? No, really, it wasn't me! :) )
// Some type of the API
struct MyType {
int i;
}
// Some function of the API that takes a delegate
void call(void delegate(MyType) dlg) {
dlg(MyType(42));
}
void main() {
/* The programmer simply copied the delegate definition from
* the function and used it as-is when passing a lambda: */
call(delegate void(MyType) {
/* WAT? Does the following really compile? After all,
* MyType.i is NOT a static member! */
if (MyType.i == 42) {
// ...
}
});
}
I was surprised to see it compiled and worked but of course MyType at
the lambda definition inside main() is not a type name, rather the
parameter name. Surprising, but I think this is according to spec.
I know this has come up before, and reported as a bug, at least once.
Might have been me :). What's confusing is that using a type that has a
keyword will make the parameter unnamed of the specified type, just as a
regular function:
auto a = (int) => 3; // works, a lambda taking an int, no parameter name
auto b = (Foo) => 3; // error, cannot infer type of template lambda
alias b = (Foo) => 3; // works, since this is an alias, Foo is the
parameter name of an unknown type
--
/Jacob Carlborg