The following code compiles and prints "1 2" as expected:
type
Expr[Mutable: static[bool], Composite: static[bool]] = object
when Mutable:
x: int
when Composite:
y: int
MutableExpr[Composite: static[bool]] = Expr[true, Composite]
var e1 = MutableExpr[true](x: 1, y: 2)
echo e1.x, " ", e1.y
However, if I add the following:
proc testMutable[Composite: static[bool]](e: MutableExpr[Composite]) =
echo e.x
testMutable(e1)
I get this compiler error:
expr.nim(20, 12) template/generic instantiation from here
expr.nim(5, 14) Error: cannot generate code for: Composite
Why? How can I define a procedure working on all MutableExpr?You could use a union type:
proc testMutable[ME: MutableExpr[true] | MutableExpr[false]](e: ME) =
echo e.x
or
type ME = MutableExpr[true] | MutableExpr[false]
proc testMutable(e: ME) = echo e.x
Not exactly elegant, but it works...
Thanks for your answer. This is however not satisfactorily: I intend to have other static parameters in the Expr class, and thus there would be a need for a combinatorial instantiation wrt all parameters...
What is the problem with my code? Why doesn't it compile? Is it a bug of the compiler, especially as static parameters are 'still in development' according to the documentation?
If it is a generics bug, you might be able to work around it using a macro or template to build up a suitable union type without hand-coding it.
# completely made up example
type ME = make_union(BaseType[A, B], (A, @[true, false]), (B, @[this, that]))
# --> type ME = BaseType[true,this] | BaseType[true,that] | ...