typedesc and expr params
types are now valid proc/template/macro params and you can overload over them:
proc foo(T: typedesc) # accept any type
proc foo(T: typedesc{int}) # overload specifically for int
proc foo(T: typedesc{int or float or Callable}) # overload for any type matching the constraints
expr{type} is a param expecting compile time value of the designated type (or type class).
when typedesc or expr params are used with a proc, the proc will be instantiated once
for each unique type/value used as parameter.
This commit is contained in:
parent
6216046bc6
commit
22dc76a361
14 changed files with 218 additions and 45 deletions
35
tests/run/ttypedesc1.nim
Normal file
35
tests/run/ttypedesc1.nim
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import unittest
|
||||
|
||||
type
|
||||
TFoo[T, U] = object
|
||||
x: T
|
||||
y: U
|
||||
|
||||
proc foo(T: typedesc{float}, a: expr): string =
|
||||
result = "float " & $(a.len > 5)
|
||||
|
||||
proc foo(T: typedesc{TFoo}, a: int): string =
|
||||
result = "TFoo " & $(a)
|
||||
|
||||
proc foo(T: typedesc{int or bool}): string =
|
||||
var a: T
|
||||
a = 10
|
||||
result = "int or bool " & ($a)
|
||||
|
||||
template foo(T: typedesc{seq}): expr = "seq"
|
||||
|
||||
test "types can be used as proc params":
|
||||
check foo(TFoo[int, float], 1000) == "TFoo 1000"
|
||||
|
||||
var f = 10.0
|
||||
check foo(float, "long string") == "float true"
|
||||
check foo(type(f), [1, 2, 3]) == "float false"
|
||||
|
||||
check foo(int) == "int or bool 10"
|
||||
|
||||
check foo(seq[int]) == "seq"
|
||||
check foo(seq[TFoo[bool, string]]) == "seq"
|
||||
|
||||
when false:
|
||||
proc foo(T: typedesc{seq}, s: T) = nil
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue