ttypetraits.nim 982 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. discard """
  2. nimout: "int\nstring\nTBar[int]"
  3. output: "int\nstring\nTBar[int]\nint\nrange 0..2(int)\nstring"
  4. disabled: true
  5. """
  6. import typetraits
  7. # simple case of type trait usage inside/outside of static blocks
  8. proc foo(x) =
  9. static:
  10. var t = type(x)
  11. echo t.name
  12. echo x.type.name
  13. type
  14. TBar[U] = object
  15. x: U
  16. var bar: TBar[int]
  17. foo 10
  18. foo "test"
  19. foo bar
  20. # generic params on user types work too
  21. proc foo2[T](x: TBar[T]) =
  22. echo T.name
  23. foo2 bar
  24. # less usual generic params on built-in types
  25. var arr: array[0..2, int] = [1, 2, 3]
  26. proc foo3[R, T](x: array[R, T]) =
  27. echo name(R)
  28. foo3 arr
  29. const TypeList = [int, string, seq[int]]
  30. macro selectType(inType: typedesc): typedesc =
  31. var typeSeq = @[float, TBar[int]]
  32. for t in TypeList:
  33. typeSeq.add(t)
  34. typeSeq.add(inType)
  35. typeSeq.add(type(10))
  36. var typeSeq2: seq[typedesc] = @[]
  37. typeSeq2 = typeSeq
  38. result = typeSeq2[5]
  39. var xvar: selectType(string)
  40. xvar = "proba"
  41. echo xvar.type.name