ocaml类,方法接受派生类

时间:2016-03-05 20:23:57

标签: class inheritance ocaml

请考虑以下代码:

module Proxy = struct
  type 'a t
end

class qObject proxy = object(self : 'self)
  method proxy : 'self Proxy.t = proxy
end

class qWidget proxy = object(self : 'self)
  inherit qObject proxy
  method add : qWidget -> unit = fun w -> ()
  method as_qWidget = (self :> qWidget)
end

class qButton proxy = object(self : 'self)
  inherit qWidget proxy
  method text = "button"
end

let qObject_proxy : qObject Proxy.t = Obj.magic 0
let qWidget_proxy : qWidget Proxy.t = Obj.magic 0
let qButton_proxy : qButton Proxy.t = Obj.magic 0

let qObject = new qObject qObject_proxy
let qWidget = new qWidget qWidget_proxy
let qButton = new qButton qButton_proxy

let () = qWidget#add qWidget
let () = qWidget#add qButton#as_qWidget

该代码输入良好并编译。但是qButton必须手动转换为qWidget,我想消除它。我希望qWidget #add接受另一个qWidget或任何派生类(如qButton)。我认为#qWidget会是正确的类型,但这不起作用:

class qWidget proxy = object(self : 'self)
  inherit qObject proxy
  method add : #qWidget -> unit = fun w -> ()
end

Error: Some type variables are unbound in this type: ...
The method add has type 'c -> unit where 'c is unbound

class qWidget proxy = object(self : 'self)
  inherit qObject proxy
  method add : 'a . (#qWidget as 'a) -> unit = fun w -> ()
end

Error: The universal type variable 'a cannot be generalized:
it escapes its scope.

我有什么办法解决这个问题吗?

1 个答案:

答案 0 :(得分:5)

我找到了解决这个问题的方法。诀窍在于add不需要从qWidget派生的对象,只需要一个可以将自身强制转换为qWidget的对象,就像使用as_qWidget方法一样。这样就可以将qWidget的必要强制转换为方法而不需要麻烦的#qWidget。

class qWidget proxy = object(self : 'self)
  inherit qObject proxy
  method add : 'a . (<as_qWidget : qWidget; ..> as 'a) -> unit
             = fun w -> let w = w#as_qWidget in ()
  method as_qWidget = (self :> qWidget)
end