有一种方法可以根据参数的类型在C ++中实现函数的特定实现。F#中有与此类似的东西吗?
简短的回答是“否”,原因在约翰链接的问题中进行了解释。
它将与方法重载一起使用,尽管它比.F#特定于.NET的更多功能。
type T = T with
static member test (x:'a list) = "Generic version"
static member test (x:int list) = "Specialized for int"
static member test (x:char list) = "Specialized for char"
> T.test ["0"] ;;
val it : string = "Generic version"
> T.test [0] ;;
val it : string = "Specialized for int"
但是使用函数没有做到这一点的干净方法,您可以找到一些技巧,例如:
type T = T with
static member ($) (a:T, x:'a list) = "Generic version"
static member ($) (a:T, x:int list) = "Specialized for int"
static member ($) (a:T, x:char list) = "Specialized for char"
let inline f a = T $ a : string
> f ["0"] ;;
val it : string = "Generic version"
> f [0] ;;
val it : string = "Specialized for int"
但这是非常有限的,它会创建一个具有静态约束的内联函数,在当前的F#版本中,该函数并不总是能够反映相同的重载分辨率,因此,我认为您无法采用这种方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句