首页 > 解决方案 > 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。

有人知道可能的解决方案吗?提前谢谢了。

标签: genericsstructconstructorf#

解决方案


您不能在结构上具有静态解析的类型参数

它们仅对内联函数有效。在这种情况下,您尝试执行的操作(将类型参数约束为需要特定方法)是不可能的。

您可以获得的最接近的方法是从结构中删除成员约束并创建为您处理结构的内联函数:

[<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

推荐阅读