How do you return a subclass instance from a base class method?
Steven Schveighoffer
schveiguy at gmail.com
Thu Nov 17 16:07:46 UTC 2022
On 11/16/22 11:25 PM, Daniel Donnelly wrote:
> I have SubclassOf derived from PosetRelation. For any poset relation,
> the transitivity law applies, however, I'd like to return the correct type:
>
> ```
> PosetRelation transitivity(PosetRelation R, PosetRelation S)
> {
> if (R.op == S.op)
> {
> if (R.right is S.left)
> return new SubclassOf(R.left, S.right);
> }
>
> return null;
> }
>
> ```
>
> How does one accomplish this in D? Because PosetRelation doesn't know
> about SubclassOf, in general.
I'd use a template:
```d
T transitivity(T : PosetRelation)(T R, T S)
{
if (R.op == S.op)
{
if (R.right is S.left)
return new T(R.left, S.right);
}
return null;
}
```
-Steve
More information about the Digitalmars-d-learn
mailing list