twildtypedesc.nim 714 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. discard """
  2. output: '''123
  3. 123
  4. 123
  5. 123
  6. 123
  7. 123'''
  8. """
  9. import strutils
  10. proc unpack(t: typedesc[string], v: string): string = $v
  11. proc unpack(t: typedesc[int], v: string): int = parseInt(v)
  12. proc unpack[T](v: string): T =
  13. unpack T, v
  14. var s = "123"
  15. doAssert(unpack[string](s) is string)
  16. doAssert(unpack[int](s) is int)
  17. echo unpack[int](s)
  18. echo unpack[string](s)
  19. echo unpack(int,s)
  20. echo unpack(string,s)
  21. template `as`*(x: untyped, t: typedesc): untyped = unpack(t,x)
  22. echo s as int
  23. echo s as string
  24. # bug #4534
  25. proc unit(t: typedesc[int]): t = 0
  26. proc unit(t: typedesc[string]): t = ""
  27. proc unit(t: typedesc[float]): t = 0.0
  28. doAssert unit(int) == 0
  29. doAssert unit(string) == ""
  30. doAssert unit(float) == 0.0