hobofan / ambassador

Delegation of trait implementations via procedural macros
Apache License 2.0
251 stars 13 forks source link

Add support for generic traits #17

Closed hobofan closed 2 years ago

hobofan commented 4 years ago

See @Cydhra's comment (https://github.com/hobofan/ambassador/issues/15#issuecomment-574470105):

use ambassador::delegatable_trait;
use ambassador::Delegate;
use num::BigUint;

struct FastSqrt;

#[delegatable_trait]
trait DiscreteSquareRootProtocol<T> {
    fn sqrt(&self, value: T, modulus: T) -> T;
}

impl<T> DiscreteSquareRootProtocol<T> for FastSqrt {
    fn sqrt(&self, value: T, modulus: T) -> T { unimplemented!() }
}

#[derive(Delegate)]
#[delegate(DiscreteSquareRootProtocol)]
struct WrapperProtocol(FastSqrt);
Cydhra commented 4 years ago

The example above does not make sense for a final draft. I used it in the other case to showcase how it does not work, but it does not make sense after all.

It should look something like this:

#[derive(Delegate)]
#[delegate(DiscreteSquareRootProtocol<T>)]
struct WrapperProtocol<T>(PhantomData<T>, FastSqrt);

or maybe even this:

#[derive(Delegate)]
#[delegate(DiscreteSquareRootProtocol<u32>)]
struct WrapperProtocol(FastSqrt);
thomaseizinger commented 4 years ago

The example above does not make sense for a final draft. I used it in the other case to showcase how it does not work, but it does not make sense after all.

It should look something like this:

#[derive(Delegate)]
#[delegate(DiscreteSquareRootProtocol<T>)]
struct WrapperProtocol<T>(PhantomData<T>, FastSqrt);

or maybe even this:

#[derive(Delegate)]
#[delegate(DiscreteSquareRootProtocol<u32>)]
struct WrapperProtocol(FastSqrt);

+1 for this syntax!

I wanted to note that there is actually two forms of generic traits that would need support here.

  1. Generics on the trait level as outlined above. Those generics would either have to be forwarded to the inner one or specified as part of the #[delegate] annotation.
  2. Generics on a trait method level. Those should be handled automatically IMO and always be forwarded. At the moment, that doesn't seem to work.
Cydhra commented 4 years ago

Generics on a trait method level. Those should be handled automatically IMO and always be forwarded. At the moment, that doesn't seem to work.

Probably just an edge case, that needs to be fixed, not a whole new feature, no?

thomaseizinger commented 4 years ago

Generics on a trait method level. Those should be handled automatically IMO and always be forwarded. At the moment, that doesn't seem to work.

Probably just an edge case, that needs to be fixed, not a whole new feature, no?

Yes exactly. That is what I meant with "those should be handled automatically" :)