Type Inference for Struct/Enum Literals - identifier literals

Nick Treleaven nick at geany.org
Thu Aug 1 16:53:42 UTC 2024


On Sunday, 7 July 2024 at 19:42:25 UTC, Nick Treleaven wrote:
> Vladimir's idea of making an identifier expression have its own 
> type

So identifier literals can be compatible with enum members, as 
discussed above. One interesting application of identifier 
literals could be for some of the situations where implicit 
construction of a user-defined type would be used in C++ - we 
don't have that in D. It could work by defining a named enum or 
static member of an aggregate type. E.g. for the struct type 
below, the `none` enum:

```d
struct Option(T) {
     enum none = Option!T.init;

     bool empty = true;
     T value;

     this(T v) {
         empty = false;
         value = v;
     }
}

void f(Option!int o)
{
     import std.stdio;
     writeln(o);
}
void main() {
     f(Option!int(5));
     f(:none); // same as `f(Option!int.none)`
}
```

I'm using `:none` as the syntax for an identifier literal. 
`typeof(:none)` could match f's argument type of `Option!int`, 
because `none` is a value member of that type. So `:none` would 
be equivalent to passing `Option!int.none` there.

So identifier literals seem more flexible than just selecting an 
enum member. They would also be useful as an argument to a mixin 
template instead of a string literal for the name of an 
identifier symbol to mixin.


More information about the dip.ideas mailing list