Home > Software engineering >  How do I make a class acting like two classes from different libraries, with basically the same func
How do I make a class acting like two classes from different libraries, with basically the same func

Time:01-29

I am currently working on a project using OpenTK and ImGui.Net.
Each of which has its own Vector2 class.

I was wondering if it was possible to create my own Vector2 class, which can be used as the other two classes without making conversion methods and can be set using the other classes.

example:

// received class: System.Numerics.Vector2()
myVector2 position = Imgui.GetWindowPosition();

// expected class: OpenTK.Mathematics.Vector2()
OpenTK.Input.Mouse.SetPosition(position.X, position.Y);

In the past I would just make an ".ToOpenTK" and a ".ToImgui" functions to convert my vector2 class to one of the asked classes and make conversion methods to convert them to my vector2 class.

The problem with this is, that I can not easily create a new vector without converting it first. Which just gives it an unnecessary extra level of complexity. It would look something like this:

vector2 position = new(100, 100).ToOpenTK();

Right now my code is a mix of both my own and the actual classes and I would like to have a universal way to use both at once.

CodePudding user response:

I do not mind explicitness and generally I prefer it, but
you could use User-defined explicit and implicit conversion operators.

A toy example:

public readonly record struct MyVector(float X, float Y)
{
    public static implicit operator System.Numerics.Vector2(MyVector v) 
       => new System.Numerics.Vector2.Vector2(x: v.X, y: v.Y);

    public static implicit operator MyVector(System.Numerics.Vector2 b) 
       => new MyVector(X: b.X, Y: b.Y);
}
  • Related