[英]Generic bound ensuring non-reference argument
The real reason to do this is beyond the scope, I just can say that it's related to a very unusual memory layout on some embedded platform.这样做的真正原因超出了 scope,我只能说这与某些嵌入式平台上非常不寻常的 memory 布局有关。 The goal is to make a wrapper for statics which can do some manual address translation on dereferencing.
目标是为静态做一个包装器,它可以在取消引用时做一些手动地址转换。 So putting a reference inside is pointless and unsafe.
所以在里面放一个引用是没有意义的,也是不安全的。 Alternatively I can make two implementations for references and not references but they must be strongly unambiguous.
或者,我可以为引用和非引用创建两个实现,但它们必须非常明确。
You can do this but it requires the nightly features negative_impls
and auto_traits
:你可以这样做,但它需要夜间功能
negative_impls
和auto_traits
:
#![feature(negative_impls)]
#![feature(auto_traits)]
auto trait NotRawRef {}
impl<T> !NotRawRef for &T {}
impl<T> !NotRawRef for &mut T {}
fn foo<T: NotRawRef>(_: T) {}
This will apply recursively by default , so T
cannot be a user-defined type that contains a reference -- unless the user-defined type explicitly implements NotRawRef
.这将默认递归应用,因此
T
不能是包含引用的用户定义类型——除非用户定义类型显式实现NotRawRef
。 You have to trust callers of your function not to implement this trait when it's not appropriate.你必须相信你的 function 的呼叫者不会在不合适的时候实现这个特性。
If nightly isn't an option, or if this is too strict, you can rather easily bound on "if there are any references, they must have static lifetime" with 'static
.如果 nightly 不是一个选项,或者如果这太严格,您可以很容易地使用
'static
绑定“如果有任何引用,它们必须具有 static 生命周期”。 For example:例如:
fn foo<T: 'static>(_: T) { }
fn main() {
let x = 1;
foo(x);
// The following line would fail with E0597:
// foo(&x);
// Works because the reference has static lifetime
foo(&1);
}
This bound applies to user-defined types that have generic lifetime parameters as well, and will reject any such type with a non- 'static
lifetime argument.此绑定也适用于具有通用生命周期参数的用户定义类型,并且将拒绝任何具有非
'static
生命周期参数的此类类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.