automatic type creation

Frustrated c1514843 at drdrb.com
Sat Jan 25 22:15:23 PST 2014


On Sunday, 26 January 2014 at 05:19:51 UTC, Ali Çehreli wrote:
> Where is the tldr; section? :)
>
> On 01/25/2014 04:08 AM, Frustrated wrote:
>
> > I'd like to support extensions of my own interfaced based
> design
> > where anyone could simply "drop" in there own inherited
> classes
> > and everything would work as if they designed everything using
> > those classes from the get go.
>
> I think the concept-based polymorphism popularized by Sean 
> Parent may be relevant.
>
> The following is an example where the "subtypes" Cat and Dog 
> are not inherited from Animal but still behave specially. The 
> design naturally allows hierarchical designs where for example 
> an Animal of Animal(Dog) can be constructed. (See the WAT? line 
> below.)
>
> import std.stdio;
>
> struct Animal
> {
>     void sing()
>     {
>         animal.sing();
>     }
>
>     this(AnimalT)(AnimalT animal)
>     {
>         this.animal = new Model!AnimalT(animal);
>     }
>
> private:
>
>     interface Interface
>     {
>         void sing();
>     }
>
>     class Model(T) : Interface
>     {
>         T t;
>
>         this(T t)
>         {
>             this.t = t;
>         }
>
>         void sing()
>         {
>             t.sing();
>         }
>     }
>
>     Interface animal;
> }
>
> struct Cat
> {
>     void sing()
>     {
>         writeln("meow");
>     }
> }
>
> struct Dog
> {
>     void sing()
>     {
>         writeln("woof");
>     }
> }
>
> void main()
> {
>     Animal[] animals = [ Animal(Cat()),
>                          Animal(Dog()),
>                          Animal(Animal(Dog())) /* WAT? :) */ ];
>
>     foreach (animal; animals) {
>         animal.sing();
>     }
> }
>
> Ali

While this is interesting I don't think it specifically addresses
the issue of having only to create the "interface" in the
original code but have it automatically create the desired type
at runtime.

In the above code you have to specify cat and dog and are simply
wrapping the desired code.

If I were using the above code it would be something like

Animal[] animals = [Animal.New(State), Animal.New(State),
Animal.New(State)];

and somehow New would use the state to know which to create(in
this case, cat, dog, and an animal wrapped dog).


(of course, the above code would be rather useless and hard to
determine the appropriate state information)



More information about the Digitalmars-d-learn mailing list