[英]Generic type parameter is not constrained when passing lifetime
为什么以下不编译?
trait A<'a> {
type Typ;
}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<'a, T, V> B for C<T> where
T: A<'a, Typ=V>
{}
前面给出了错误“类型参数V
不受 impl trait、self 类型或谓词的约束”。 将关联类型更改为泛型类型也不会编译,并给出相同的错误。 但是,当生命周期被删除时,以下编译。
trait A {
type Typ;
}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<T, V> B for C<T> where
T: A<Typ=V>
{}
删除关联的类型也会编译。
trait A<'a> {}
trait B {}
struct C<T> {
_ph: std::marker::PhantomData<T>,
}
impl<'a, T> B for C<T> where
T: A<'a>
{}
看到删除生命周期如何导致代码编译(不以任何方式更改 V),我猜测错误消息不是真正的潜在错误。 我不知道不编译的真正原因是什么。
最初出现的情况并不真正相关 - 这个问题更多的是关于奇怪的行为和错误消息,但如果你愿意,你可以在这里查看。
它抱怨是因为你没有限制那个泛型。
这就像写:
impl<A> SomeTrait for MyType {}
// We aren't using A
这将工作得很好,因为它已经通用于Typ
是什么:
impl<'a, T> B for C<T> where
T: A<'a>,
{
// you can refer to your V type as <T as A>::Typ
}
如果你确实想限制它,你可以:
use std::default::Default;
impl<'a, T> B for C<T> where
T: A<'a>,
<T as A<'a>>::Typ: Default,
{
// now here you can call <T as A<'a>>::Typ::default()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.