Whats the cleanest way to define procs that work on stack or heap objects?
I don't want to cause allocations with a box function and the syntax isnt great with deref refs or addresses of objects at the call site.
The received wisdom currently in c++ is to use a raw pointer in the function signature where the function doesnt take ownership.
At a guess I want a ref to automatically convert to a pointer?
Thanks
How about this?
type
Obj = object
x: int
y: int
Ref = ref Obj
RefOrObj = Ref or Obj
proc init(arg: var RefOrObj, x, y: int) =
when arg is ref:
new(arg)
arg.x = x
arg.y = y
proc sum(arg: RefOrObj): int =
arg.x + arg.y
proc main() =
var o: Obj
var r: Ref
init(o, 1, 1)
echo sum(o)
init(r, 2, 2)
echo sum(r)
main()
These procedures essentially are generics that work either for the base type or the reference type.