Can a D library have some types determined by the client program?
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Fri Mar 8 03:19:59 UTC 2024
On 08/03/2024 4:09 PM, Liam McGillivray wrote:
> On Thursday, 7 March 2024 at 22:18:40 UTC, Richard (Rikki) Andrew
> Cattermole wrote:
>> There are two ways to do this.
>>
>> 1. Use templates. https://tour.dlang.org/tour/en/basics/templates
>> 2. Use a factory function.
>> https://tour.dlang.org/tour/en/basics/delegates
>>
>> ```d
>> class Map(ATile : Tile) {
>> ATile[] tiles;
>> }
>> ```
>
> Thank you. Is this first example you gave the template? Is the syntax
> `(ATile : Tile)` saying that ATile must be a derived class of Tile? If
> this isn't worse in any way than your second example, then I don't know
> why I wouldn't choose this one.
Typically in D we use templates quite heavily, but what you are wanting
is probably more familiar to you via the OOP method with a factory of
some kind.
> I suppose that if I do this, then the derived class `Mission` would be
> declared like `class Mission : Map(GridTile)`, right?
``class Mission : Map!GridTile`` but right idea.
> When I tried adding that parameter to the Map class, on attempting to
> build it it complained that references to Map in other classes were
> incomplete, as they didn't include a parameter. I suppose I must make my
> other classes templates too.
>
> Something strange that I just realized is that (without doing any of the
> changes you suggested to me), I have a reference to a Map object as one
> of the class variables in Unit, yet it has allowed me to place a Mission
> object in it's place. It no longer allows me if I change it to a
> pointer. Why is it sometimes possible to put a derived class in a place
> meant for the class it inherits from?
That should always be allowed.
More information about the Digitalmars-d-learn
mailing list