Say I have a two classes and a procedure that modifies either class in the same manner. How do I specify that a parameter can be either class (instead of rewriting or overloading the 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, things work 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's easy to rewrite the function. But I'm looking to do this for more complex classes and procedures. In some cases inheritance might be appropriate, but it doesn't seem like Nim classes can be passed as variables to procedures in place of the base class.
A bracket fixes this problem, otherwise the var
just applies to Class1[T]
:
proc addToX[T](c: var (Class1[T]|Class2[T]), val: T) =
You may run into another compiler bug with this later: https://github.com/nim-lang/Nim/issues/1385
Maybe in your use case object variantes or inheritance and methods will work better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With