Let's say I have two classes and a procedure that equally modifies any class. How to indicate that a parameter can be either a class (instead of overwriting or overloading a function for each class)? A simple example:
type
Class1[T] = object
x: T
Class2[T] = object
x: T
y: T
# this works fine
proc echoX[T](c: Class1[T]|Class2[T]) =
echo c.x
# this does not work
proc addToX[T](c: var Class1[T]|Class2[T], val: T) =
c.x += val
var c1: Class1[int]
var c2: Class2[int]
# this works fine
echoX(c1)
echoX(c2)
# this does not work
addToX(c1, 10)
addToX(c2, 100)
I get the following error.
Error: for a 'var' type a variable needs to be passed
If I use a separate procedure for each class, everything works fine.
proc addToX[T](c: var Class1[T], val: T) =
c.x += val
proc addToX[T](c: var Class2[T], val: T) =
c.x += val
This is just a simple example where it is easy to rewrite a function. But I want to do this for more complex classes and procedures. In some cases, inheritance may be appropriate, but it does not look like Nim classes can be passed as variables to procedures instead of the base class.
source
share