F#通用结构构造函数和错误FS0670

时间:2018-11-06 15:56:41

标签: generics struct constructor f#

我在StackOverflow中发现了关于错误FS0670(This code is not sufficiently generic. ...)的一些问题,但是所提出的解决方案都无法很好地解决我的问题(我是初学者,也许我错过了F#的某些概念)。 / p>

我具有以下通用结构,仅适用于基本类型(即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。

有人知道可能的解决方案吗?预先非常感谢。

1 个答案:

答案 0 :(得分:3)

您不能在结构上使用How to delete all the entries from google datastore?

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

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

[<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
相关问题