尼姆。如何继承不同类型的所有操作?

Her*_*ott 4 nim-lang

假设,我有type Radians = distinct float并且type Degrees = distinct float
这不允许我使用可用于浮点数的所有操作,甚至是最基本的算术,+有 什么方法可以对它们进行排序并仅用于编译时检查吗?-*
distinct

hol*_*ola 6

查看nim 手册上不同类型的建模货币部分以获取完整示例。

总之:

使用借用编译指示

proc `*` (x: int, y: Dollar): Dollar {.borrow.}
proc `div` (x: Dollar, y: int): Dollar {.borrow.}
Run Code Online (Sandbox Code Playgroud)

使用模板减少样板文件

template multiplicative(typ, base: typedesc) =
  proc `*` *(x: typ, y: base): typ {.borrow.}
  proc `*` *(x: base, y: typ): typ {.borrow.}
  proc `div` *(x: typ, y: base): typ {.borrow.}
  proc `mod` *(x: typ, y: base): typ {.borrow.}
Run Code Online (Sandbox Code Playgroud)