简体   繁体   中英

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. 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 :

#![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 . You have to trust callers of your function not to implement this trait when it's not appropriate.


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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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