How to implement a trait for a generic type of function pointer, no matter whose arguments types are references or not

Viewed 153

I want: for a trait, e.g. Foo, any fn(T1,T2)->() should implement it, and I don't care whether T1 or T2 is a reference or not.

trait Foo {
    fn hello_world(&self) -> String {
        "hello world".into()
    }
}
impl<T1, T2> Foo for fn(T1, T2) -> () {}

fn a_dummy_sample_function(_: i32, _:i32) {}

fn main() {
    let fn_ptr : fn(i32, i32)->() = a_dummy_sample_function;
    (fn_ptr).hello_world();
}

So far, it works well.

If I change the type of first argument to &i32,

trait Foo {
    fn hello_world(&self) -> String {
        "hello world".into()
    }
}
impl<T1, T2> Foo for fn(T1, T2) -> () {}

fn foo_imp(_: &i32, _:i32) {}

fn main() {
    let fn_ptr : fn(&i32, i32)->() = foo_imp;
    fn_ptr.hello_world();
}

Then, I've got the following compilation errors.

  --> src/main.rs:12:12
   |
12 |     fn_ptr.hello_world();
   |            ^^^^^^^^^^^ method not found in `for<'r> fn(&'r i32, i32)`
   |
   = note: `fn_ptr` is a function, perhaps you wish to call it
   = help: items from traits can only be used if the trait is implemented and in scope
note: `Foo` defines an item `hello_world`, perhaps you need to implement it

I can fix the compilation error as below

impl<T1, T2> Foo for for<'a> fn(&'a T1, T2) -> () {}

But it is not what I want, I want any function pointer with any types of two arguments whether it is a reference or not.

0 Answers
Related