【发布时间】:2013-02-09 02:04:11
【问题描述】:
考虑以下代码:
type Base(x : float) =
member this.x = x
static member (~-) (a : #Base) = Base(-a.x)
static member Cos (a : #Base) = Base(cos a.x)
type Inherited(x : float) =
inherit Base(x)
let aBase = Base(5.0)
let aInherited = Inherited(5.0)
-aBase // OK, returns Base(-5.0)
-(aInherited :> Base) // OK, returns Base(-5.0)
-aInherited // not OK
最后一行产生错误:
error FS0001: This expression was expected to have type
Inherited
but here has type
Base
与cos aInherited 相同:它给出相同的错误,但-(aInherited :> Base) 和cos (aInherited :> Base) 可以工作。
错误消息表明这些函数希望- 或cos 的返回类型与参数类型相同。这似乎是一个过于苛刻的要求。
- 对于从定义运算符的基类型继承的类,除非重新定义每个运算符,否则这是不可能的。
- 如果这些类驻留在您无法控制的外部库中,那么您的选择就会更加有限。
有没有办法解决这个问题?在F#源码中,cos函数定义在prim-types.fs中。
【问题讨论】: