tcompositetypeclasses.nim 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. template accept(e) =
  2. static: assert(compiles(e))
  3. template reject(e) =
  4. static: assert(not compiles(e))
  5. type
  6. TFoo[T, U] = tuple
  7. x: T
  8. y: U
  9. TBar[K] = TFoo[K, K]
  10. TUserClass = int|string
  11. TBaz = TBar[TUserClass]
  12. var
  13. vfoo: TFoo[int, string]
  14. vbar: TFoo[string, string]
  15. vbaz: TFoo[int, int]
  16. vnotbaz: TFoo[RootObj, RootObj]
  17. proc foo(x: TFoo) = echo "foo"
  18. proc bar(x: TBar) = echo "bar"
  19. proc baz(x: TBaz) = echo "baz"
  20. accept foo(vfoo)
  21. accept bar(vbar)
  22. accept baz(vbar)
  23. accept baz(vbaz)
  24. reject baz(vnotbaz)
  25. reject bar(vfoo)
  26. # https://github.com/Araq/Nim/issues/517
  27. type
  28. TVecT*[T] = array[0..1, T]|array[0..2, T]|array[0..3, T]
  29. TVec2* = array[0..1, float32]
  30. proc f[T](a: TVecT[T], b: TVecT[T]): T = discard
  31. var x: float = f([0.0'f32, 0.0'f32], [0.0'f32, 0.0'f32])
  32. var y = f(TVec2([0.0'f32, 0.0'f32]), TVec2([0.0'f32, 0.0'f32]))
  33. # https://github.com/Araq/Nim/issues/602
  34. type
  35. TTest = object
  36. TTest2* = object
  37. TUnion = TTest | TTest2
  38. proc f(src: ptr TUnion, dst: ptr TUnion) =
  39. echo("asd")
  40. var tx: TTest
  41. var ty: TTest2
  42. accept f(addr tx, addr tx)
  43. reject f(addr tx, addr ty)