generics - F# 通用结构构造函数和错误 FS0670
问题描述
我在 StackOverflow 中发现了一些关于错误 FS0670 ( This code is not sufficiently generic. ...
) 的问题,但是建议的解决方案都不能很好地解决我的问题(我是初学者,也许我错过了 F# 的一些概念)。
我有以下通用结构,我只想使用原始类型(即 int16/32/64 和 single/float/decimal)。
[<Struct>]
type Vector2D<'T when 'T : struct and 'T:(static member get_One: unit -> 'T) and 'T:(static member get_Zero: unit -> 'T) > =
val x : 'T
val y : 'T
new( xp: 'T, yp: 'T ) = { x = xp; y = yp }
但是使用新的构造函数,我得到了提到的错误 FS0670。
有人知道可能的解决方案吗?提前谢谢了。
解决方案
您不能在结构上具有静态解析的类型参数。
它们仅对内联函数有效。在这种情况下,您尝试执行的操作(将类型参数约束为需要特定方法)是不可能的。
您可以获得的最接近的方法是从结构中删除成员约束并创建为您处理结构的内联函数:
[<Struct>]
type Vector2D<'T when 'T : struct> =
val x : 'T
val y : 'T
new( xp: 'T, yp: 'T ) = { x = xp; y = yp }
let inline create< ^T when ^T : struct and ^T:(static member get_One: unit -> ^T) and ^T:(static member get_Zero: unit -> ^T)> (x : ^T) (y : ^T) =
Vector2D< ^T> (x, y)
create 2.0 3.0 |> ignore
create 4 5 |> ignore
推荐阅读
- yandex - 多个 x 值的 RunningDifference(x)
- javascript - 检测用户检查并删除整个 div
- unity3d - 奖励广告回调未触发
- android - 在我的 CategoryAdapter 中遇到问题?无法整理
- c++ - 使用 .cpp 文件让 RcppArmadillo 在 Rstudio 中工作
- javascript - Chrome 扩展:在文档按钮上单击运行 browser_action
- postgresql - Keycloak Docker 集群未从 JDBC_PING 数据库中删除
- caption - Premier pro 翻转 srt 字母的顺序
- java - 工厂设计模式 - 在子类中定义方法
- react-native - ReferenceError: raygunUtilityFactory 未定义