Hello everyone, I define a new type ft32, but it is inconvenient when assigning it, and it cannot be automatically converted,code show as below
template additive(typ: typedesc) =
proc `+` *(x, y: typ): typ {.borrow.}
proc `-` *(x, y: typ): typ {.borrow.}
# unary operators:
proc `+` *(x: typ): typ {.borrow.}
proc `-` *(x: typ): typ {.borrow.}
proc `+` *(x: typ, y: SomeNumber): typ = x+y.typ
proc `+` *(x: SomeNumber, y: typ): typ = x.typ+y
proc `-` *(x: typ, y: SomeNumber): typ = x-y.typ
proc `-` *(x: SomeNumber, y: typ): typ = x.typ-y
template multiplicative(typ, base: typedesc) =
proc `*` *(x: typ, y: base): typ {.borrow.}
proc `*` *(x: base, y: typ): typ {.borrow.}
proc `/` *(x: typ, y: base): typ {.borrow.}
proc `*` *(x: typ, y: SomeNumber): typ = x*y.typ
proc `*` *(x: SomeNumber, y: typ): typ = x.typ*y
proc `/` *(x: typ, y: SomeNumber): typ = x/y.typ
proc `/` *(x: SomeNumber, y: typ): typ = x.typ/y
template comparable(typ: typedesc) =
proc `<`*(x, y: typ): bool {.borrow.}
proc `<=`*(x, y: typ): bool {.borrow.}
proc `==`*(x, y: typ): bool {.borrow.}
proc `<` *(x: typ, y: SomeNumber): bool = x < y.typ
proc `<` *(x: SomeNumber, y: typ): bool = x.typ < y
proc `<=` *(x: typ, y: SomeNumber): bool = x <= y.typ
proc `<=` *(x: SomeNumber, y: typ): bool = x.typ <= y
proc `==` *(x: typ, y: SomeNumber): bool = x == y.typ
proc `==` *(x: SomeNumber, y: typ): bool = x.typ == y
template defineCurrency(typ, base: untyped) =
type
typ* = distinct base
additive(typ)
multiplicative(typ, base)
comparable(typ)
defineCurrency(ft32, float32)
defineCurrency(ft33, float32)
proc `$`*(f: ft32): string = result = fmt("{f.float32:1.2f}")
proc `$`*(f: ft33): string = result = fmt("{f.float32:1.3f}")
var a=1.ft32
a=1 #error
a=1.0.float32 #error
a=2.ft32 # ok, Why is there no automatic conversion here, or do I need to add some conversion code?
var b=1.float32
b=2 #Why can it be automatically converted here?
converter toFt32(n: int): ft32 =
ft32(n)
var a: ft32 = 1
a = 2