On Fri, Mar 15, 2019 at 10:30:41PM +0000, eXodiquas via Digitalmars-d-learn 
wrote:
> On Friday, 15 March 2019 at 21:46:50 UTC, Ali Çehreli wrote:
[...]
> > Or use template constraints:
> > 
> > struct Vector {
> >   Vector opBinary(string op)(Vector rhs)
> >     if (op == "+") {
> >       return Vector();
> >     }
> > 
> >   double opBinary(string op)(Vector rhs)
> >     if (op == "/") {
> >       return 0.5;
> >     }
> > }
> > 
> > Ali
> 
> Thanks for the quick and simple answers, but I don't get this one. If
> I do it that way the compiler doesn't know which function to call, or
> am I doing something wrong?
> 
> Vector2 opBinary(string op)(Vector2 rhs) {
>         if (op == "+") {
>             return Vector2(this.x + rhs.x, this.y + rhs.y);
>         } else if (op == "-") {
>             return Vector2(this.x - rhs.x, this.y - rhs.y);
>         }
>     }
> 
>     float opBinary(string op)(Vector2 rhs) {
>         if (op == "*") {
>             return this.x * rhs.x + this.y * rhs.y;
>         }
>     }
> 
> This gives me the error:
> overloads (Vector2 rhs) and (Vector2 rhs) both match argument list for
> opBinary
[...]

Ali's example was unfortunately deceptively formatted. The `if` has to
be *outside* the function body; it's not a regular if-statement, but a
signature constraint. And there is no `else` clause to it.

        Vector opBinary(string op)(Vector rhs)
                if (op == '+' || op == '-')
        {
                /* function body begins here */
                ...
        }

        double opBinary(string op)(Vector rhs)
                if (op == '*')
        {
                /* function body begins here */
                ...
        }


T

-- 
Notwithstanding the eloquent discontent that you have just respectfully 
expressed at length against my verbal capabilities, I am afraid that I must 
unfortunately bring it to your attention that I am, in fact, NOT verbose.

Reply via email to