Interface Limitations in D

Alexandru Ermicioi alexandru.ermicioi at gmail.com
Mon Sep 20 18:08:03 UTC 2021


On Monday, 20 September 2021 at 13:24:50 UTC, Elmar wrote:
> Providing default implementation support seems not more 
> difficult:
>
> ```D
> mixin Interface!("MyInterface",
> q{
>     static immutable PI = 3.141592f;
>     default static immutable CONSTANT = 0.0f;
>
>     float toImplement(string s);
>
>     default float isDefaulted()
>     {
>         return (CONSTANT ^^ PI) % toImplement(r"tau"));
>     }
> });
> ```
>
> Providing default method implementations without code 
> duplication and too much verbosity could work by defining the 
> default method implementations as **compile-time token 
> strings**. The above would generate

You can actually try use mixin templates, not just mixin strings. 
See https://dlang.org/spec/template-mixin.html .

It has nicer syntax although not as powerful as mixin strings. 
You can also mix in the template into a dedicated scope inside 
implementor of interface:

```
mixin MyDefaultImpl!() myScope;
```

I didn't try it, but you may be able to mimic default methods 
using this feature, in conjunction with alias this expression, 
although I'm pretty skeptic about this due to mangled name 
generation (i.e haven't tried it).

So in your class you may try and explore whether this works:

```
mixin MyDefaultImpl!() def;

alias this def;
```





More information about the Digitalmars-d mailing list