Operator Overloading in an Abstract Base Class

IgorStepanov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 20 14:35:50 PST 2014


On Thursday, 20 November 2014 at 22:10:28 UTC, Nordlöw wrote:
> In my module symbolic.d at
>
> https://github.com/nordlow/justd/blob/master/symbolic.d
>
> is it somehow possible to overload binary operator ~ on pairs 
> of instances SPatt?
>
> I'm asking because my current try at
>
> https://github.com/nordlow/justd/blob/master/symbolic.d#L332
>
> is not called in the unittest at
>
> https://github.com/nordlow/justd/blob/master/symbolic.d#L347
>
> Isn't it possible to do operator overloading in an abstract 
> base-class?

Seq opBinary(string op)(Patt rhs)
{
     static if (op == "~")
     {
         return seq(this, rhs);
     }
     else
     {
         static assert(false, "Unsupported binary operator " ~ op);
     }
}

As far I understood your question, you want to override opBinary 
in a derived class?
You can't do it directly, because opBinary is template and 
template can not be overriten. However, you may declare virtual 
non-template method for "~" and call it from opBinary.

And `static if (op == "~")` is not good. Use template constraint 
instead:

class Patt
{
     // It is better then your static if.
     // Compiler will raise better error message for incorrect 
operator.
     Seq opBinary(string op)(Patt rhs) if (op == "~")
     {
         return opCatImpl(rhs);
     }

     protected Seq opCatImpl(Patt rhs) //you may override it in 
derived class
     {
         return seq(this, rhs);
     }
}


More information about the Digitalmars-d-learn mailing list