tstackconcept.nim 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. discard """
  2. output: "20\n10"
  3. nimout: '''
  4. INFERRED int
  5. VALUE TYPE int
  6. VALUE TYPE NAME INT
  7. IMPLICIT INFERRED int int
  8. IMPLICIT VALUE TYPE int int
  9. IMPLICIT VALUE TYPE NAME INT INT
  10. '''
  11. """
  12. import typetraits, strutils
  13. template reject(e) =
  14. static: assert(not compiles(e))
  15. type
  16. ArrayStack = object
  17. data: seq[int]
  18. proc push(s: var ArrayStack, item: int) =
  19. s.data.add item
  20. proc pop(s: var ArrayStack): int =
  21. return s.data.pop()
  22. type
  23. Stack[T] = concept var s
  24. s.push(T)
  25. s.pop() is T
  26. type ValueType = T
  27. const ValueTypeName = T.name.toUpperAscii
  28. proc genericAlgorithm[T](s: var Stack[T], y: T) =
  29. static:
  30. echo "INFERRED ", T.name
  31. echo "VALUE TYPE ", s.ValueType.name
  32. echo "VALUE TYPE NAME ", s.ValueTypeName
  33. s.push(y)
  34. echo s.pop
  35. proc implicitGeneric(s: var Stack): auto =
  36. static:
  37. echo "IMPLICIT INFERRED ", s.T.name, " ", Stack.T.name
  38. echo "IMPLICIT VALUE TYPE ", s.ValueType.name, " ", Stack.ValueType.name
  39. echo "IMPLICIT VALUE TYPE NAME ", s.ValueTypeName, " ", Stack.ValueTypeName
  40. return s.pop()
  41. var s = ArrayStack(data: @[])
  42. s.push 10
  43. s.genericAlgorithm 20
  44. echo s.implicitGeneric
  45. reject s.genericAlgorithm "x"
  46. reject s.genericAlgorithm 1.0
  47. reject "str".implicitGeneric
  48. reject implicitGeneric(10)