Spice allows overloading operators for custom struct types. Currently, this works for the operators +, -, *, /, ==, !=, <<, >>, +=, -=, *=, /=, ++ (postfix) and -- (postfix). In the future, more operators will be supported for overloading.
typeSizealiaslong;typeCounterstruct{Sizevalue}pCounter.ctor(longinitialValue=0l){this.value=initialValue;}f<Size>Counter.getValue(){returnthis.value;}/** * Here we define the plus operator for lhs of type Counter and rhs of type Counter * * @param c1 Counter 1 * @param c2 Counter 2 * @return New counter with the sum of c1 and c2 */f<Counter>operator+(constCounter&c1,constCounter&c2){returnCounter(c1.value+c2.value);}f<int>main(){Countercounter1=Counter(2l);Countercounter2=Counter(3l);printf("Counter1 value: %d\n",counter1.getValue());printf("Counter2 value: %d\n",counter2.getValue());Countercounter3=counter1+counter2;// Here we call the overloaded operatorprintf("Counter3 value: %d\n",counter3.getValue());}