Compile delegate with enum into proper function?

Tejas notrealemail at gmail.com
Sun May 8 07:44:59 UTC 2022


On Saturday, 7 May 2022 at 18:36:40 UTC, jmh530 wrote:
> In the code below, there is a two parameter function `foo` and 
> an override of it with only one parameter. In the override 
> case, I force the second one to be 1, but ideally there should 
> be a way to specify it at compile-time.
>
> It would be kind of nice to be able to do it with an enum and a 
> delegate or something, perhaps like `foo2`. However, that is 
> still generating a delegate. Something like `foo3` also works, 
> but I can't create that within a main function like I can for 
> the delegate.
>
> I suppose the question is why can't I tell the compiler to 
> compile a delegate into a proper function? I suppose this also 
> holds for a function pointer. The difference I suppose is that 
> the delegate with enums isn't really taking advantage of the 
> features of a delegate, at least as far as I can tell.
>
> ```d
> int foo(int x, int a) {
>     return x + a;
> }
>
> int foo(int x) {
>     return x + 1;
> }
>
> enum int a = 1;
> auto foo2 = (int x) => {foo(x, a)};
> int foo3(int x) {
>     return x + a;
> }
> ```

>
```d
  auto foo2 = (int x) => {foo(x, a)};

```

Why did you use the `{ }` when you already used `=>`???
The following code compiles `foo2` as a function

```d
int foo(int x, int a)  @nogc
{
     return x + a;
}

int foo(int x)
{
     return x + 1;
}

enum int a = 1;
auto foo2 = (int x) @nogc => foo(x, a);

int foo3(int x)
{
     return x + a;
}

void main()@nogc
{
     foo2(5);
     pragma(msg, typeof(foo2)); //int function(int x) @nogc @system
}
```

I still recommend using my default argument values solution 
though if it is feasible.


More information about the Digitalmars-d-learn mailing list