我的几个模块包含全局类实例,这些实例使用两种方法实现给定的类类型: private_method
和public_method
。
我要MyModule.my_instance # public_method
可从我的程序中的任何位置使用,并且 MyModule.my_instance # private_method
仅在MyModule
内可用。
我尝试了以下操作:
class type public_type = object
method public_method : int
end ;;
class type private_type = object
method public_method : int
method private_method : int
end ;;
let make_private : unit -> private_type = fun () -> object
method public_method = 0
method private_method = 0
end ;;
module type MY_MODULE = sig
val my_instance : public_type
end
module MyModule : MY_MODULE = struct
let my_instance = make_private ()
let _ = print_int (my_instance # private_method)
end
但是,这会导致错误:
Values do not match:
val my_instance : private_type
is not included in
val my_instance : public_type
我可以手动编写强制转换:
module MyModule : MY_MODULE = struct
let my_instance = make_private ()
let _ = print_int (my_instance # private_method)
let my_instance = (my_instance :> public_type)
end
但是我不想为了像这样简单的事情而将代码大小加倍。
您对为什么会发生这种情况以及如何解决它有什么建议吗?
最佳答案
ocaml 中没有隐式强制转换。也许值得将强制转换放入仿函数中(如果您有多个具有相同属性的模块):
module Hide(M:sig val my_instance : private_type end) : MY_MODULE =
struct
let my_instance = (M.my_instance :> public_type)
end
module MyModule = Hide (struct
let my_instance = make_private ()
let _ = print_int (my_instance # private_method)
end)
关于module - 模块签名中的类实例类型强制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4647063/