[英]How can I have static dispatch for a linked list containing different types all implementing a trait?
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.替换问号的类型实现了Renderable
,但它不一定是R
,它可能是T: Renderable
例如。 I would like to avoid any solution using dyn Renderable
, to keep the static dispatch.我想避免使用dyn Renderable
任何解决方案,以保持静态调度。
The type T: Renderable
is known at Layer
instantiation and won't change.类型T: Renderable
在Layer
实例化时已知并且不会改变。
TL;DR : It is impossible (at least w/o variadic generics *) TL;DR :这是不可能的(至少没有可变泛型*)
Right now Layer
structure requires 2
generic parameters: R
and 'a
.现在Layer
结构需要2
通用参数: R
和'a
。
Let's imagine we found the right type for /* ? */
假设我们找到了/* ? */
的正确类型/* ? */
/* ? */
. /* ? */
。 Let's name it T0
.我们将其命名为T0
。
Then Layer
structure will require 3
generic parameters: T0
, R
and 'a
.然后Layer
结构将需要3
通用参数: T0
、 R
和'a
。
Then you have to provide one more generic parameter for parent
field.然后你必须parent
字段提供一个更多的通用参数。 Let's name it T1
.我们将其命名为T1
。
Then Layer
structure will require 4
generic parameters: T1
, T0
, R
and 'a
.然后Layer
结构将需要4
通用参数: T1
、 T0
、 R
和'a
。
Then you have to provide one more generic parameter for parent
field.然后你必须parent
字段提供一个更多的通用参数。 Let's name it T2
.我们将其命名为T2
。
<...> <...>
Layer
structure will require i+2
generic parameters: Ti
, Ti-1
, ... T1
, T0
, R
and 'a
.然后Layer
结构将需要i+2
通用参数: Ti
、 Ti-1
、... T1
、 T0
、 R
和'a
。parent
field.然后你必须parent
字段提供一个更多的通用参数。 Let's name it Ti+1
.我们将其命名为Ti+1
。Layer
structure will require i+1+2
generic parameters: Ti+1
, Ti
, Ti-1
, ... T1
, T0
, R
and 'a
.然后Layer
结构将需要i+1+2
通用参数: Ti+1
、 Ti
、 Ti-1
、... T1
、 T0
、 R
和'a
。 At the end, you have infinite recursion.最后,你有无限递归。 Additional generic parameter for parent
field have to be defined as a part of Layer
structure.必须将parent
字段的附加通用参数定义为Layer
结构的一部分。 That induce introduction of a new generic parameter for Layer
.这会为Layer
引入一个新的通用参数。 That induce additional generic parameter for parent
field.这会parent
字段引入额外的通用参数。
To break up recursion, additional generic parameter for parent
shouldn't be a part of Layer
definition.为了分解递归, parent
附加泛型参数不应成为Layer
定义的一部分。 If a parameter is not a part of Layer
definition then we can't calculate Layer
size at compile time.如果参数不是Layer
定义的一部分,那么我们无法在编译时计算Layer
大小。 The way it may be solved is &dyn
or Box
.解决它的方法是&dyn
或Box
。
*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. *另一种可能的解决方案是可变泛型,但看起来我们至少在接下来的几个月甚至几年内都不会拥有它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.