On Wednesday, 14 June 2017 at 22:29:08 UTC, Balagopal Komarath wrote:
On Wednesday, 14 June 2017 at 21:04:55 UTC, basile b. wrote:
The way to do that in D is with mixins:

That is an interesting solution.

However, my original goal was to figure out whether one can make struct types behave polymorphically (Which is not mentioned in my original question). I know that this is not supported by design. I want to keep the original struct types but also allow functions to accept those struct types and do runtime dispatch. The following code should give a better idea by what I mean by this.

https://dpaste.dzfl.pl/051f6a4da059

The user need only define Duck1, Duck2 ... with appropriate functions and mixin toDuck. Then a function that accepts a Duck can accept DuckLike (for dynamic dispatch) or templatize on the type of Duck.

Duck typing doesn't work with the pattern you used initially.
The pattern you used initially is much more similar to the solution i exposed.

The point is that "alias" cant do what you wished.
It's not in the language, end of story.

Finally duck types in D are more like this:

enum looksLikeaDuck(T) = __traits(hasMember, T, "quack");

class Test(T)
if (looksLikeaDuck!T)
{
    T data;
    alias data this;
}

struct Duck
{
    void quack()
    {
        import std.stdio;
        writeln("Quack");
    }
}

void main()
{
    Test!Duck d;
}

you use traits to verify that the template parameter looks like a duck.
It's not like in Swift where an aggregate is used.
In D we use traits (even if traits can be used to verify that a template parameter is compliant with the member of an aggregate).

Reply via email to