nim-lang - 无法进行早期绑定的 Nim 模板?
问题描述
库中定义了build_type
模板。lib.nim
template build_type*[T](_: type[T]): T = T.build()
该对象B
使用该模板来构建对象A
。
而且它不起作用 - 因为虽然在A
中可见,但在使用的地方b.nim
不可见。main.nim
B
如果A
导入main.nim
(请参阅注释掉的导入),它会起作用,但感觉不对,因为它破坏了B
内部细节的封装(因为使用的代码B
也应该导入A
,即使它不使用A
)。
我想知道是否有其他方法可以使它工作?
# main.nim ------------------------------------------
import bobject #, aobject
echo B.build()
# bobject.nim ---------------------------------------
import lib, aobject
type B* = tuple[a: A]
proc build*(_: type[B]): B = (a: build_type(A))
# aobject.nim ---------------------------------------
type A* = tuple[v: int]
proc build*(_: type[A]): A = (0,)
# lib.nim -------------------------------------------
template build_type*[T](_: type[T]): T = T.build()
编译错误:
/main.nim(3, 7) template/generic instantiation of `build` from here
/bobject.nim(5, 44) template/generic instantiation of `build_type` from here
/lib.nim(1, 43) Error: type mismatch: got <type A>
but expected one of:
proc build(_: type[B]): B
first type mismatch at position: 1
required type for _: type B
but expression 'T' is of type: type A
expression: build(T)
解决方案
我会使其工作更改bobject.nim
为:
proc initB*(): B =
(a: build_type(A))
并固定main.nim
到:
echo initB()
推荐阅读
- laravel - 带有 reactJs 的 Laravel 5.6 中的 419 个未知状态
- javascript - 如何在 R 网站抓取中处理 onclick javascript 事件
- svg - 如何从SVG路径中的另一条线以直角绘制一条线
- c++ - C++ 2D 网格数组,从文件中读取和插入数组值
- javascript - NodeJs 对象合并基于键值 Id
- django - 在 DetailView 上使用表单,将数据提交到 FormView - 包括来自 DetailView 上下文的数据
- c# - c#中的Windows按钮圆角
- maven - JUnit5 通过标签运行测试
- django - Django:捕获完整性错误与 qs.exists() 哪个更有效?
- php - 当 csrf 保护为真时,从 codeigniter 3 中的 ajax 发送数据显示 403 禁止