gpt4 book ai didi

class - 具有接受派生类的方法的 ocaml 类

转载 作者:行者123 更新时间:2023-12-05 00:56:45 24 4
gpt4 key购买 nike

考虑以下代码:

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.

有什么方法可以解决我没有看到的问题吗?

最佳答案

我找到了解决这个问题的方法。诀窍是 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

关于class - 具有接受派生类的方法的 ocaml 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com