Hi. I have a template with vararg[untyped] parameters, can I get count of parameters and realize branching like a:
template tmpl*(args: varargs[untyped]): untyped =
when args.len > 0: # here is compilation will be excepted
#...
else:
#...
Thanks.At the very least, you can dispatch with macros at compile time. Not sure about the template issue.
macro tmpl*(args: varargs[untyped]): untyped =
if args.len > 0:
result = quote do: foo
else:
result = quote do: bar
As far as I know, using a macro is the only way you can work with an untyped(see also in the manual: https://nim-lang.org/docs/manual.html#templates-varargs-of-untyped )
If you want to stringify each parameter, or want to apply another proc which converts the all into the same type, you can simply write varargs[typed, yourProc] (e.g. echo uses varargs[typed, `$`]
If you want to have a variadic with different types for each parameter, you can also use a unspecified tuple:
proc takeVariadics(params: tuple) =
var i = 0
for field in fields(params):
when field is int:
echo "param ", i, " is an int"
elif field is string:
echo "param ", i, " is a string"
else:
{.error: "only strings and ints allowed!".}
inc i
echo "first call"
takeVariadics(()) # nothing
echo "second call"
takeVariadics((_: 42))
echo "last call"
takeVariadics((10, "a", "b", 12))
IMHO would it be great to adopt generic variadics similar to the ones found in C++. But for the time being unspecified tuples and macros with untyped varargs demonstrate how flexible and powerful Nim's generics are.