作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写某种序列化库(为了学习 F#)。现在我坚持这样做:
假设我们已经有了一些基本类型的序列化函数:
type StoreOps =
static member inline store(x:int) = ...
static member inline store(x:int64) = ...
static member inline store(x:float) = ...
static member inline store(x:float32) = ...
static member inline store(x:bool) = ...
static member inline store(x:string) = ...
....
现在我想实现泛型函数来存储任何基本类型的数组:
let inline store(x:'T[]) =
x |> Array.iter StoreOps.store
,但编译器无法编译它(错误消息说:无法根据此程序点之前的类型信息确定方法“store”的唯一重载
)。
在 F# 中实现此类功能的正确方法是什么?因为我不想为 int[]
、bool[]
、float[]
...
最佳答案
首先,您可能不需要在接受特定类型参数的定义上inline
。其次,简短的回答可能是“没有好的方法来做到这一点”。但是,如果您愿意容忍可怕的黑客攻击,您可以执行以下操作:
type StoreOps =
... // everything you've currently got
let inline storeArray< ^t, ^u when (^t or ^u) : (static member store : ^u -> unit)> arr =
arr
|> Array.iter (fun x -> ((^t or ^u) : (static member store : ^u -> unit) x))
type StoreOps with
static member inline store arr = storeArray<StoreOps,_> arr
您还可以将 storeArray
助手设为私有(private)(如果您不想公开它,请使用 let inline private storeArray...
。
关于f# - F# 中的泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604371/
我是一名优秀的程序员,十分优秀!