General problem I'm having in D with the type system

Neia Neutuladh neia at ikeran.org
Sun May 27 21:16:46 UTC 2018


On Sunday, 27 May 2018 at 20:50:14 UTC, IntegratedDimensions 
wrote:
> The only problem where it can leak is when we treat an cat as 
> an animal then put in dog food in to the animal, which is valid 
> when cat as treated as an animal, then cast back to cat. Now 
> cat has dog food, which is invalid.

It sounds like you don't want to have a `food` setter in the 
`Animal` base class. Instead, you want setters in each child 
class that take the specific type required, and possibly an 
abstract getter in the base class. You could use a mixin to ease 
the process of defining appropriate food types, and you could 
have a method that takes the base `Food` class and does runtime 
validation.

You might also change `Animal` to `Animal!(TFood : Food)` and go 
from there. You'd likely need to extract another base class or 
interface so you can have a collection of arbitrary animals.


More information about the Digitalmars-d mailing list