ocaml类,方法接受派生类

Gos*_*low 4 inheritance ocaml class

请考虑以下代码:

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
Run Code Online (Sandbox Code Playgroud)

该代码打印良好并编译.但是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
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

有没有办法绕过这个我没看到的?

Gos*_*low 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
Run Code Online (Sandbox Code Playgroud)