I have a proc with auto argument type with works for any object type I pass to it. But I need to make 5 different calls of that proc for each object type.
So I am looking for a way to optimize that, and this pseudocode is what I have:
type
Foo = object
someInt: int
someStr: string
Bar = object
someBool: bool
someStr: string
proc doSomething(obj: auto): string =
$obj
let
foo = Foo(someInt: 1000, someStr: "abc")
bar= Bar(someBool: true, someStr: "def")
echo doSomething(foo)
echo doSomething(bar)
# Trying to get something like below to work -- need help
#[[
macro printAllObjs(objs: varargs[untyped]): untyped =
var
str: string
for obj in objs:
str.add(doSomething(obj))
str.add("\n")
echo str
printAllObjs(foo, bar)
]]#
https://play.nim-lang.org/#ix=44We
What would be the correct way to write that macro?
Thanks!
You don't need a macros to do that, you can directly use varargs with a proc call :
proc printAllObjs(objs: varargs[string, doSomething]) =
var str: string
for obj in objs:
str.add obj
str.add("\n")
echo str
printAllObjs(foo, bar)
Thanks!
You are right! I don't need a macro here. This works (and I think that that will work for my actual code as well).
type
Foo = object
someInt: int
someStr: string
Bar = object
someBool: bool
someStr: string
proc doSomething(obj: auto): string =
$obj
let
foo = Foo(someInt: 1000, someStr: "abc")
bar= Bar(someBool: true, someStr: "def")
# echo doSomething(foo)
# echo doSomething(bar)
proc printAllObjs(objs: varargs[string, doSomething]): string =
for obj in objs:
result.add obj
result.add "\n"
echo printAllObjs(foo, bar)