ttempl3.nim 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. discard """
  2. action: compile
  3. """
  4. template withOpenFile(f: untyped, filename: string, mode: FileMode,
  5. actions: untyped): untyped =
  6. block:
  7. # test that 'f' is implicitly 'injecting':
  8. var f: File
  9. if open(f, filename, mode):
  10. try:
  11. actions
  12. finally:
  13. close(f)
  14. else:
  15. quit("cannot open for writing: " & filename)
  16. withOpenFile(txt, "ttempl3.txt", fmWrite):
  17. writeLine(txt, "line 1")
  18. txt.writeLine("line 2")
  19. var
  20. myVar: array[0..1, int]
  21. # Test zero argument template:
  22. template ha: untyped = myVar[0]
  23. ha = 1
  24. echo(ha)
  25. # Test identifier generation:
  26. template prefix(name): untyped = `"hu" name`
  27. var `hu "XYZ"` = "yay"
  28. echo prefix(XYZ)
  29. template typedef(name: untyped, typ: typeDesc) {.immediate, dirty.} =
  30. type
  31. `T name`* = typ
  32. `P name`* = ref `T name`
  33. typedef(myint, int)
  34. var x: PMyInt
  35. # Test UFCS
  36. type
  37. Foo = object
  38. arg: int
  39. proc initFoo(arg: int): Foo =
  40. result.arg = arg
  41. template create(typ: typeDesc, arg: untyped): untyped = `init typ`(arg)
  42. var ff = Foo.create(12)
  43. echo ff.arg