Virtual opBinary in interface
mzfhhhh
mzfhhhh at foxmail.com
Fri Dec 20 01:33:12 UTC 2024
On Thursday, 19 December 2024 at 18:49:28 UTC, sfp wrote:
> Subject lines says it all, I think... The choice to make binary
> operators implementable only via this `opBinary` template means
> it's unclear how to get virtual operators on an interface.
> E.g., this toy example *does* compile:
> ```
> interface Scalar {
> Scalar opBinary(string op)(Scalar rhs); // wrong
> }
>
> class Int : Scalar {
> int i;
> this(int i) { this.i = i; }
> Int opBinary(string op)(Int rhs) if (op == "+") {
> return new Int(i + this.i);
> }
> }
>
> void main() {
> Scalar one = new Int(1);
> Scalar two = one + one;
> }
> ```
The template methods in the interface need to be implemented
within the interface.
https://dlang.org/spec/interface.html#method-bodies
```d
interface Scalar {
Scalar opBinary(string op)(Scalar rhs) if (op == "+") {
return add(rhs);
}
Scalar add(Scalar rhs);
}
class Int : Scalar {
int i;
this(int i) { this.i = i; }
Scalar add(Scalar rhs) {
return new Int((cast(Int)rhs).i + this.i);
}
}
void main() {
Scalar one = new Int(1);
Scalar two = one + one;
}
```
More information about the Digitalmars-d-learn
mailing list