I have this working code:
struct Layer<'a> {
parent: Option<Box<Layer<'a>>>,
value: Box<dyn Renderable + 'a>,
}
I would like to have a version using static dispatch instead:
struct Layer<'a, R: Renderable> {
parent: Option<&'a Layer<'a, /* ? */>>,
value: R,
}
The type replacing the question mark implements Renderable
, but it's not necessarily R
, it could be T: Renderable
for example. I would like to avoid any solution using dyn Renderable
, to keep the static dispatch.
The type T: Renderable
is known at Layer
instantiation and won't change.
TL;DR: It is impossible (at least w/o variadic generics*)
Right now
Layer
structure requires2
generic parameters:R
and'a
.Let's imagine we found the right type for
/* ? */
. Let's name itT0
.Then
Layer
structure will require3
generic parameters:T0
,R
and'a
.Then you have to provide one more generic parameter for
parent
field. Let's name itT1
.Then
Layer
structure will require4
generic parameters:T1
,T0
,R
and'a
.Then you have to provide one more generic parameter for
parent
field. Let's name itT2
.<...>
Layer
structure will requirei+2
generic parameters:Ti
,Ti-1
, ...T1
,T0
,R
and'a
.parent
field. Let's name itTi+1
.Layer
structure will requirei+1+2
generic parameters:Ti+1
,Ti
,Ti-1
, ...T1
,T0
,R
and'a
.At the end, you have infinite recursion. Additional generic parameter for
parent
field have to be defined as a part ofLayer
structure. That induce introduction of a new generic parameter forLayer
. That induce additional generic parameter forparent
field.To break up recursion, additional generic parameter for
parent
shouldn't be a part ofLayer
definition. If a parameter is not a part ofLayer
definition then we can't calculateLayer
size at compile time. The way it may be solved is&dyn
orBox
.*The other possible solution is variadic generics but it looks like we will not have it at least for next few months or even years.