Operator Overloading with multiple return types

eXodiquas exodiquas at gmail.com
Fri Mar 15 22:30:41 UTC 2019


On Friday, 15 March 2019 at 21:46:50 UTC, Ali Çehreli wrote:
> On 03/15/2019 02:43 PM, Sebastiaan Koppe wrote:
>> On Friday, 15 March 2019 at 21:35:12 UTC, eXodiquas wrote:
>>> Is there any way to achive this behaivour with D2?
>> 
>> Yep. Just make the return type in the function declaration 
>> `auto`. You are then free to return a different type in each 
>> static branch.
>
> 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

eXodiquas


More information about the Digitalmars-d-learn mailing list