Custom binary operators

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Sat Dec 28 07:18:56 PST 2013


Is there any way with D to define custom binary operators for user-defined 
types?  I'm thinking of examples like MATLAB/Octave using the operators .+, .-, 
etc. to define element-wise addition, subtraction, etc. of matrices.

AFAICS just doing something like

     auto opBinary(string op, T)(T rhs)
         if (op == ".+")
     {
         ...
     }

... won't work, because the parser won't accept a code line like

     auto c = a .+ b;

... but is there some way to make this work?

Assuming that it's not possible to define custom operators in regular code, I 
guess the alternative is to use templates to ensure an override of the regular + 
operator?


More information about the Digitalmars-d-learn mailing list