Hi Hackers,
I need to apply different logic in template if the argument has a particular type or is untyped expression. Calling getType() in macro triggers compilation failure for untyped expression.
Ideally, something like this. Any ideas are appreciated.
template filter(expr : untyped) =
when type(expr) is seq[bool]: # currently causes compilation failure if expr is untyped
.....
elif type(expr) is seq[int]:
....
else: # expression has no type, inject additional variables to make expression typed
....
Thank you
type(expr) -> expr:
template filter(expr: untyped) =
when expr is seq[bool]: echo "bool"
elif expr is seq[int]: echo "int"
else: discard
filter newSeq[int]()
I don't know if this is useful for your usecase tho.I need something that not going to cause compilation error for the case when expr does not have a type
template filter(expr: untyped) =
when expr is seq[bool]: echo "bool"
elif expr is seq[int]: echo "int"
else: discard
filter(a + b) # a and b are not defined, hence no type.
# Should gracefully go to else statement, but currently causes compilation error
like this
template filter(expr: untyped) =
when compiles(expr):
when expr is seq[bool]: echo "bool"
elif expr is seq[int]: echo "int"
else: echo "something else"
else:
echo "can't compile"
filter(a + b)
Thank you,
compiles(expr) is geniune feature, too bad compiles() is not mentioned in the language manual