0

I'm trying to write a macro to work on each of the types inside a tuple type. The tuple type is passed from the generic type parameter of a function to the macro.

eg

fn print_type_ids<T:'static>() { my_macro!(T); }

print_type_ids::<(i32,f32,&str)>() should print the 3 different type ids.

But I can't match inside the Tuple Type when it is passed as a generic type param to the macro.

My code so far:

macro_rules! my_macro {
    ( ($($x:ty),+) ) => {
        {
            $(
                println!("{:?}",std::any::TypeId::of::<$x>());
            )+
        }
    };
}

fn print_type_ids<T:'static>() {
    my_macro!(T); //error, no match for this
}

fn main() {
    print_type_ids::<(i32,f32)>();

    my_macro!((i32,f32)); //works, prints twice, once for each type
}

I found two examples that look like they should solve my problem, but failed to understand what they are doing.

one from Serde

let (log, operation_state_id) = serde_json::from_slice::<(String, String)>(serialized_tuple.as_bytes()).unwrap();

second from rust-num

let t : (u32, u16) = num::Bounded::max_value();
Grob
  • 3
  • 3

1 Answers1

0

macro_rules! my_macro2 {
    ($($x:ty,)* ) => {
        {
            $(
                println!("{:?}",std::any::TypeId::of::<$x>());
            )*
        }
    };
}

trait Happy {
    fn go();
}

macro_rules! tuple_impls {
    ( $head:ident, $( $tail:ident, )* ) => {
        impl<$head, $( $tail ),*> Happy for ($head, $( $tail ),*)
        where
            $head: 'static,
            $( $tail: 'static ),*
        {
            fn go() {
                my_macro2!($head, $( $tail, )*);
            }
        }

        tuple_impls!($( $tail, )*);
    };

    () => {};
}

tuple_impls!(A, B, C,D, E, F, G, H, I, J,);

fn print_type_ids<T:'static+Happy>() {
    T::go();
}

fn main() {
    print_type_ids::<(i32,f32,usize)>();
}

Borrowed some code from here

Grob
  • 3
  • 3