opBinary : Static ifs or specialization?

Meta jared771 at gmail.com
Wed Jun 24 00:51:21 UTC 2020


On Tuesday, 23 June 2020 at 23:53:36 UTC, claptrap wrote:
> So you have opBinary and half a dozen operators to implement. 
> Do you use a separate method for each operator or do you have 
> one method and a big static if else if to select code path?
>
> I assume they are functionally equivalent? So its just about 
> style?

An idiomatic example:

import std.algorithm: among;

struct Test
{
     int payload;

     Test opBinary(string op)(Test other)
     if (op.among!("+", "-", "*", "/")) //Limit supported ops
     {
         mixin("return Test(payload " ~ op ~ "other.val);");
     }

     int opBinary(string op)(int n)
     //No constraint; support the full range of integer operations
     {
         mixin("return payload " ~ op ~ "n;");
     }
}


More information about the Digitalmars-d-learn mailing list