IC_
IC_

Reputation: 1839

Nim. How to inherit all operations on distinct type?

Suppose, I have type Radians = distinct float and type Degrees = distinct float
This is not allowing me to use all operations available for floats, even most basic arithmetics +, -, *
Is there any way to sort of 'inherit' them all and use distinct only for compile-time checks?

Upvotes: 4

Views: 599

Answers (1)

hola
hola

Reputation: 3500

Check the Modeling Currencies section from the Distinct type on the nim manual for the full example.

In summary:

Use the borrow pragma

proc `*` (x: int, y: Dollar): Dollar {.borrow.}
proc `div` (x: Dollar, y: int): Dollar {.borrow.}

Use templates to reduce boilerplate

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.}

Upvotes: 6

Related Questions