+ 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.
2 odpowiedzi
+ 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.
+ 1
Decided to play:
https://code.sololearn.com/cRfFxqW3NgVK