Frist Draft (in this forum): Enum Parameters

Quirin Schroll qs.il.paperinik at gmail.com
Thu Apr 25 23:29:59 UTC 2024


On Thursday, 25 April 2024 at 20:29:27 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
> […]
>
> If however it resulted in that function parameter being treated 
> as a template parameter that would be different. But I don't 
> see anything that suggests this.

But that is exactly what I propose.

Quoting from the draft:

> In the function body (including contracts and constraints), an 
> `enum` parameter’s value is a compile-time constant as if it 
> were template value parameter.
> The same is true for `this` in an `enum` non-`static` member 
> function body.
> The main difference between `enum` parameters and template 
> value parameters is only in calling syntax:
> `f!ct_value(args)` versus `f(ct_value, args)`.
> Another difference is that the type of an `enum` parameter can 
> be inferred, while a template value parameter must have its 
> type specified.

It would allow to define `opIndex` as
```d
struct Tpl(Ts...)
{
     Ts[i] opIndex(enum size_t i) { .. }
     Tpl!(Ts[l..u]) opSlice(enum size_t l, enum size_t u) { .. }
}
```
So that
```d
Tpl!(int, string, Object) t;
t[0] // lowers to t.opIndex(0) of type int
t[1] // lowers to t.opIndex(1) of type string
t[2] // lowers to t.opIndex(2) of type Object
t[3] // lowers to t.opIndex(3), a compile error as 
(int,string,Object)[3] fails
t[0..2] // is of type Tpl!(int, string)
```

You could have `opBinary` that only accepts certain constants to 
add.
Or `opEquals` that only allows for comparison with `0`.
`regex` could simply “notice” that the pattern is a compile-time 
constant and be equivalent to `ctRegex`.
`format` can check and/or optimize if the pattern is a 
compile-time constant.

Maybe with interpolated strings, there’s a lot possible. I don’t 
know. If you find some application, please let me know.


More information about the dip.development mailing list