首页 > 解决方案 > 无法进行早期绑定的 Nim 模板?

问题描述

库中定义了build_type模板。lib.nim

template build_type*[T](_: type[T]): T = T.build()

该对象B使用该模板来构建对象A

而且它不起作用 - 因为虽然在A中可见,但在使用的地方b.nim不可见。main.nimB

如果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)

标签: nim-lang

解决方案


我会使其工作更改bobject.nim为:

proc initB*(): B =
  (a: build_type(A))

并固定main.nim到:

echo initB()

推荐阅读