简体   繁体   English

为所有使用 const 参数实现特性的类型实现特性

[英]Implementing a trait for all types implementing a trait with const parameter

I believe that the following code makes sense:我相信以下代码是有道理的:

trait FooConst<const N: usize> {}
trait Foo {}

impl<T: FooConst<N>, const N: usize> Foo for T {}

However when I try to compile it I get error E0207 stating that the parameter N is unbounded.但是,当我尝试编译它时,我收到错误 E0207,指出参数N是无界的。 I don't understand why, since it seems to me that it's part of the bound on T .我不明白为什么,因为在我看来它是T绑定的一部分。

Playground link 游乐场链接

The fundamental reason why this is not allowed is because the trait bounds may cause multiple trait implementations for the same type.不允许这样做的根本原因是因为 trait bound 可能会导致同一类型的多个 trait 实现。

For example, consider a type Bar that implements both FooConst<1> and FooConst<2> , which is perfectly fine:例如,考虑一个同时实现FooConst<1>FooConst<2> Bar类型,这是非常好的:

struct Bar;

impl FooConst<1> for bar {}
impl FooConst<2> for bar {}

If Foo is implemented for all T: FooConst<N> , then we get two Foo implementations for Bar : one for N == 1 and one for N == 2 .如果Foo对所有实现T: FooConst<N>那么我们得到两个Foo为实现Bar :一个用于N == 1 ,一个用于N == 2 Rust does not allow the possibility of having multiple trait implementations, which is why it disallows using type parameters in this way. Rust 不允许有多个 trait 实现,这就是为什么它不允许以这种方式使用类型参数。

One way to work around this is to instead make N an associated constant:解决此问题的一种方法是将N设为关联常量:

trait FooConst {
    const N: usize;
}
trait Foo {}

impl<T: FooConst> Foo for T {
    // T::N is an associated constant   
}

Ok, so I do not exactly know why this works while your code does not work, but here's a code that does what you want :好的,所以我不完全知道为什么这会在您的代码不起作用时起作用,但是这里有一个代码可以满足您的要求:

trait FooConst<const N: usize> {}
trait Foo {}

impl<const N: usize> Foo for dyn FooConst<N> {}

Feel free leaving a comment if you know why this works.如果您知道为什么会这样,请随时发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM