How to use overloaded explicit conversion operators?

I have a type defined in C # like this:

struct F { public static explicit operator F(long value) {} public static explicit operator long(F value) {} public static explicit operator F(double value) {} public static explicit operator double(F value) {} // more conversion operators } 

In F #, if I want to create it from long, the only way I have found is:

 let l = F.op_Explicit 3L 

I tried to create an inline function to make it more enjoyable:

 let inline fa = F.op_Explicit a 

But this does not compile. I also tried with member limitation:

 let inline f (x:^a) = (F: (static member op_Explicit : ^a -> F) x) 

And this also does not compile.

Is it possible to define a function or operator to select the correct overload?

On a side note, it works great in the opposite direction:

 let f = someF |> int64 // calls the right conversion operator 
+6
source share
1 answer

It is not valid to have an element constraint on one particular type; however, this may work for you:

 let inline f (x:^a) : F = let inline gx = ((^b or ^c):(static member op_Explicit : ^b -> ^c) x) gx 

This has a more general type f : ^a -> F when ( ^a or F) : (static member op_Explicit : ^a -> F) , which is a type that cannot manually annotate any value with!

+4
source

All Articles