The year is 2019

XavierAP n3minis-git at yahoo.es
Sat Jul 27 11:30:33 UTC 2019


On Saturday, 27 July 2019 at 09:38:20 UTC, Mike Franklin wrote:
> On Saturday, 27 July 2019 at 05:09:11 UTC, XavierAP wrote:
>
>>     interface IPrintable
>>     {
>>         string toString();
>>     }
>
> I like the idea of using interfaces, but I'm not sure how to 
> implement such a thing for structs.  Is it just a compile-time 
> contract?  How does it work at runtime when we call a function 
> like `void foo(IPrintable p);` with an instance of `XY` or 
> `ParallelXY`?

Indeed the options and their consequences have to be studied. In 
principle I would constrain it, again no virtual dispatch 
whatsoever, and keep the value semantics. We can take a look at 
how C# already does it. I think Go has a similar feature.

But imo it should imply polymorphism (e.g. in function parameter 
types) as you ask.

And it's not only at runtime, or rather the border line between 
compile time and run time can be different for each program. 
Because unlike classes, structs are statically instantiated, the 
examples you ask may be ver well evaluating at ct, e.g.

     enum XY p = { 1, 2 };
     enum s = p.toString();

But note also that interfaces in structs would be a separate 
feature/DIP from struct inheritance (from other structs, not 
interfaces).

And given the extensive preference in the current D crowd (and in 
Phobos) for templates, there's no big use case for structs 
implementating interfaces, as there is however imo for 
inheritance.

> Are you suggesting the body of `XY` simply be copied into 
> `ParallelXY`?  I think that can already be done with template 
> mixins.

Indeed I know you can implement these simple features building on 
the more complex (and macro-ish), but it shouldn't be done this 
way, and that was my point.

What I am suggesting is to implement new into the language the 
very simple inheritance that already exists for classes, or the 
same that C++ has for its RAII classes/structs.

An inherited type includes (contains, memory-wise) the base type. 
The additional members defined in the derived type declaration 
are aligned after the inherited ones. That's why the derived type 
can also be used anywhere in place of the base one (polymorphism).

Implementing this simple feature from template mixins does not 
guarantee this memory alignment. Plus imo it's wrong to build a 
brick out of houses.

Here you have an example I wrote with (macro-ish) template 
mixins, while it would vave been much better with (private) 
inheritance:

https://github.com/XavierAP/femd/blob/master/src/algebra/statics.d

Amd here's another example where inheritance would have been 
better than composition:

https://github.com/XavierAP/game-king/blob/master/source/sdl_help.d


More information about the Digitalmars-d mailing list