#Const generics as argument to macro

3 messages · Page 1 of 1 (latest)

tropic quiver
#

I'm trying to write a macro for implementing a trait on a type. However, some of the types have const generic arguments, so i would like to be able to pass these as a second argument to the macro. The following is my attempt, where the first usage works but the second doesn't:

macro_rules! impl_trait {
    ($type:ty,$generics:tt) => {
        impl<$generics> FooTrait for $type {}
    };
}
struct FooBar<T>(T);
impl_trait!(FooBar<T>, T);

struct Bar<const N: usize>;
impl_trait!(Bar<N>, const N: usize);

I have tried other ways of denoting the second argument, but none of them have worked.

unborn fable
#

There is no meta matcher for that part of the syntax you would need to build it yourself from either groups of token trees or directly matching via more macro arms

tropic quiver
#

Thanks. This seems to do the job, but seems tricky to generalize:

macro_rules! impl_trait {
    ($type:ty,$(const $gen:tt: $t:ty),*) => {
        impl<$(const $gen: $t),*> FooTrait for $type {}
    };
}

struct Bar<const N: usize, const M: usize>;
impl_trait!(Bar<N, M>, const N: usize, const M: usize);