What is :-) ?

Paul Backus snarwin at gmail.com
Mon Nov 20 16:47:13 UTC 2023


On Monday, 20 November 2023 at 16:09:33 UTC, Antonio wrote:
> What "breaks" my mind is that a compiler decision (treat a 
> piece of code as function or delegate) is not completely 
> transparent causing "side" effects on your code  (writeln 
> doesn't work the same way:  it shows the delegate signature, 
> but not the function signature).

It's certainly surprising that `writeln` treats function pointers 
and delegates differently. My guess is that it's because 
[`isPointer`][1] returns `true` for functions and `false` for 
delegates.

[1]: https://phobos.dpldocs.info/std.traits.isPointer.html

> Is there any way to force D compiler to treat this 
> "createCounter" declaration as **delegate** instead of 
> **function**?
>
> ```d
>   auto createCounter = (int nextValue) => () => nextValue++;
> ```

You can put the `delegate` keyword in front of the function 
literal:

```d
auto createCounter = delegate (int nextValue) => () => 
nextValue++;
```

This syntax is documented in the spec's section on [Function 
Literals][2] (look at the grammar box and the examples).

[2]: https://dlang.org/spec/expression.html#function_literals


More information about the Digitalmars-d-learn mailing list