How to require operator overloading in interface

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jul 19 07:52:45 PDT 2013


On Fri, Jul 19, 2013 at 04:28:42PM +0200, Adam D. Ruppe wrote:
> You can't have templates in interfaces unless they are final,
> otherwise it won't work right.
> 
> The way I'd do it is is make the op template final, and have it
> forward to another normal virtual function:
> 
> interface Addable {
>    final Addable opBinary(string op : "+")(Addable rhs) {
>         return this.opAdd(rhs);
>    }
> 
>    /* virtual */ Addable opAdd(Addable rhs);
> }
> 
> class Test : Addable {
>     override Addable opAdd(Addable rhs) {
>             return new Test();
>     }
> }
[...]

I'd add that you need to do this for base classes too, if you want
overloaded operators to be overridable by derived classes. Template
methods and inheritance don't mix together very well.


T

-- 
The diminished 7th chord is the most flexible and fear-instilling chord.
Use it often, use it unsparingly, to subdue your listeners into
submission!


More information about the Digitalmars-d-learn mailing list