Syntax used for operator overloading in a generic class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Syntax used for operator overloading in a generic class

Hi everyone, I have created a generic class Position with two values, x and y, and I want to overload the + operator to add two Position variables and return their sum. For now, my class looks like this: Class Position<T> { public T x { get; set; } public T y { get; set; } Position(T x, T y) { this.x = x; this.y = y; } //operator function declaration { return (new Vector<T>(a.x + b.x, a.y + b.y)); } } If there are any mistakes in my actual code, please tell me too.

10th Sep 2018, 4:39 PM
UltraN
2 Answers
+ 2
Generic types lose all aspects of their type that are not available to all types. Since addition doesn't work on all types, you can't do it with anything of type T. You need to remember I could create a Position<Boolean> legally, which doesn't support addition. My way around this is to pass in a callback on creation. When I need things like which is greater or addition, I call the corresponding callback function to do the work. I do have a C# operator overloading example, which you could get the correct syntax from. I don't have any generics in C# only Kotlin. I am willing to help more, if you need it. Please link your code here using the plus with the circle around it icon or share the link to copy to the clipboard and paste it into your reply.
11th Sep 2018, 2:16 PM
John Wells
John Wells - avatar
11th Sep 2018, 3:28 PM
John Wells
John Wells - avatar