How do I overload += operator?
    Jack 
    jckj33 at gmail.com
       
    Mon Jan 25 17:09:22 UTC 2021
    
    
  
I'd like to make this work s += 10 where s is a struct. How can I 
do that?
this isn't working:
     auto ref opAssign(string op, T)(T value)
     if(op == "+")
     {
         m += value;
         return this;
     }
the compiler didn't consider that overload and return:
d.d(34): Error: s is not a scalar, it is a S
full code:
     auto s = S(10);
     writeln(--s);
     s += 5;
     writeln(s);
struct S
{
     int m;
     int opUnary(string op)()
     {
         static if(op == "--")
             return --m;
         else static if(op == "++")
             return ++m;
         else
             static assert(0, "unsupported operator");
     }
     void opBinary(string op, R)(const R rhs)
     if(op == "+")
     {
         m += rhs;
         return this;
     }
     auto ref opAssign(string op, T)(T value)
     if(op == "+")
     {
         m += value;
         return this;
     }
}
    
    
More information about the Digitalmars-d-learn
mailing list