Avoid writing repeated code for different numeric types in .NET.

I am trying to write a generic type Vector2 that will contain types float, double, etc. and use arithmetic operations. Is there any way to do this in C #, F #, Nemerle, or any other more or less mature .NET language?

I need a solution with

  • (1) good performance (the same thing that I would write separately Vector2Float, Vector2Double, etc.),
  • (2) which would allow the code to look good (I don't want to allocate code for each class at runtime)
  • (3) and which will do as much compilation time as possible.

For reasons 1 and 3, I would not want to use dynamics. Now I am checking out F # and Nemerle.

UPD: I expect that I will have a lot of math code for this type. However, I would prefer to put the code in extension methods, if possible.

UPD2: etc. include int (which I really doubt that I will use) and decimal (I think I can use, but not now). Using extension methods is just a matter of taste - if there are good reasons not to, please let me know.

+3
source share
6 answers

Daniel, F # , , , .NET- #. , inline, F # ( ++), F # .

, inline:

let inline add x y = x + y;;    

:

val inline add :
  x: ^a -> y: ^b ->  ^c
    when ( ^a or  ^b) : (static member ( + ) :  ^a *  ^b ->  ^c)

, - , , + ( .NET). , , .

, , , F #. , #, , F #, F # ( # ). F #.

+8

. , static Create.

[<Struct>]
type Vector2D<'a> private (x: 'a, y: 'a) =
  static member inline Create<'a  when 'a : (static member (+) : 'a * 'a -> 'a)>(x, y) = Vector2D<'a>(x, y)
+3

# , . , .

, , , "" - . AssemblyBuilder Vector2 #, . , (.. OpenTK, SharpDX). ilmerge, .

, ++, . , Vector2, , "" . , Vector2, .

+1

.

+1

, , , . Nemerle , . DSL . , , .

def vec = vector { [1,2] };

, VectorInt,

def vec = VectorInt(1,2);

, , :)

. Nemerle , F #.

0

Generics,

Additional information on generics: http://msdn.microsoft.com/en-us/library/512aeb7t.aspx

But you also have data structures available, such as List and Dictionary

It looks like you want operator overloading , there are many examples for this. There is not a very good way to resolve decial, float, etc. The only thing you can do is to limit the structure, but that is not quite what you want.

-2
source

All Articles