module - 模块签名中的类实例类型强制

标签 module ocaml signature coercion

我的几个模块包含全局类实例,这些实例使用两种方法实现给定的类类型: private_methodpublic_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/

相关文章:

class - 使用其他方法创建 Ocaml 子类的正确方法是什么?

python - 复制签名,转发包装函数的所有参数

c# - 不使用BouncyCaSTLe的C#中的数字签名

module - PrestaShop 中的延迟加载页面?

ruby-on-rails - 具有相同名称的类和模块 - 如何选择一个或另一个?

ruby - 创建 Ruby gem//'require' 错误 : cannot load such file (LoadError)

linux - GDB 找不到行号

Char 与 int 调用约定

OCamlbuild 和构建原生动态链接库

java - java ab中动态绑定(bind)和签名方法的问题