【发布时间】:2011-01-10 12:58:17
【问题描述】:
我的几个模块包含全局类实例,这些实例通过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
但是,这会导致错误:
值不匹配:
val my_instance : private_type不包含在
中
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
但我宁愿不要将这样简单的代码大小加倍。
您对为什么会发生这种情况以及我如何解决它有什么建议吗?
【问题讨论】:
标签: module ocaml signature coercion