Interface Limitations in D

Elmar chrehme at gmx.de
Mon Sep 20 15:37:39 UTC 2021


On Monday, 20 September 2021 at 11:45:06 UTC, Ogi wrote:
> On Sunday, 19 September 2021 at 20:00:11 UTC, Elmar wrote:
>> * **Non-polymorphic inheritance exists (`alias this` in 
>> `struct`s or `class`es) but no non-polymorphic `interface`s 
>> for structs**
>>
>>    This one is most meaningful.
>>
>>    In my current project in D, I'm working on a low or 
>> medium-low level and it's not suitable to use classes (they 
>> also need to work in Better-C). I don't need polymorphy. I 
>> only like to guarantee a **consistent** interface among my 
>> `struct`s. It makes life of users easier and prohibits others 
>> from "inheriting" my struct properties in unintended ways.
>>
>
> Sounds like what 
> [concepts](https://code.dlang.org/packages/concepts) package 
> does. Unfortunately, doesn’t work with BetterC.

Nice suggestion! `@implements` looks like solving most parts of 
my current problem.
But of course, BetterC is a key feature of D and not supporting 
it (even the standard library) reduces the usability of BetterC.

Although they provide most of the functionality, they don't 
provide the syntax for it which I find important, more important 
than compiler message goals stated by the "Concept" package. When 
I first saw signatures for ranges, I found the long-ish 
`if`-constraints unpleasantly verbose for something which really 
should look just like:

```D
size_t count(InputRange r)
{

}
```

instead of

```D
size_t count(Range)(Range r)
     if (isInputRange!Range)
{

}
```

But of course, the main point is the functionality: being able to 
constraint struct implementations like with an interface for 
classes. The "Concept" package makes this easier (even though the 
predicate is still manually defined there).

Even more pleasant would be a type which is treated as 
`interface` when applicable and fallbacks to a template otherwise 
which statically asserts certain members. It would optimize away 
a lot of template bloat in those cases where it's not required, 
like with class-types.

```D
bool createWith(out MyObject obj, Allocator alloc)
{

}
```

The `GCAllocator` doesn't implement an interface but some can 
implement `IAllocator`. It would be useful to fallback to a 
template for types which provide basic Allocator methods but 
don't implement `IAllocator`.

Do only I think, that interface-like type names for some 
trait-predicates could improve the readability a lot? One could 
get rid of repetitively defining these predicates manually.


More information about the Digitalmars-d mailing list