automatic type creation
Ali Çehreli
acehreli at yahoo.com
Sat Jan 25 21:19:49 PST 2014
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
More information about the Digitalmars-d-learn
mailing list