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
Layerstructure requires2generic parameters:Rand'a.Let's imagine we found the right type for
/* ? */. Let's name itT0.Then
Layerstructure will require3generic parameters:T0,Rand'a.Then you have to provide one more generic parameter for
parentfield. Let's name itT1.Then
Layerstructure will require4generic parameters:T1,T0,Rand'a.Then you have to provide one more generic parameter for
parentfield. Let's name itT2.<...>
Layerstructure will requirei+2generic parameters:Ti,Ti-1, ...T1,T0,Rand'a.parentfield. Let's name itTi+1.Layerstructure will requirei+1+2generic parameters:Ti+1,Ti,Ti-1, ...T1,T0,Rand'a.At the end, you have infinite recursion. Additional generic parameter for
parentfield have to be defined as a part ofLayerstructure. That induce introduction of a new generic parameter forLayer. That induce additional generic parameter forparentfield.To break up recursion, additional generic parameter for
parentshouldn't be a part ofLayerdefinition. If a parameter is not a part ofLayerdefinition then we can't calculateLayersize at compile time. The way it may be solved is&dynorBox.*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.