簡體   English   中英

如何將包含多個項目的宏傳遞到宏?

[英]How to pass a macro containing multiple items into a macro?

鑒於這個擴展多個項目的簡單宏,如何將宏作為參數?

macro_rules! print_structs {
    ($($t:ty)*) => ($(
        println!("{:?}", TypeId::of::<$t>());
    )*)
}

// expands one println per type!
print_structs! { i8 i16 usize String }

如何傳入預定義的類型宏?

非工作宏的示例:

macro_rules! some_types {
    () => {
        i8 i16 usize String
    }
}

print_structs! { some_types!() }

請參閱play.rust-lang.org示例,取消注釋UNCOMMENT TO TEST行以查看問題。

給出錯誤: macro expansion ignores token `i16` and any following


我還嘗試將列表放在一個文件中,例如:

print_structs! {
    include!("some_types.in")
}

...但是這給出了一個錯誤: expected type, found `include!("../struct_list.rs")`

從這看起來,似乎不可能使用宏或include擴展宏內的列表。

雖然代碼生成是一種選擇,但它非常復雜,所以會將其排除在此答案之外。

可以通過交換宏使用來獲得類似的功能,而不是將列表傳遞到宏中,將宏名稱傳遞給通用宏,使用列表擴展它。

下面是一個有效的例子:

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

macro_rules! apply_macro_to_structs {
    ($macro_id:ident) => {
        $macro_id! {
            i8 i16 usize String
        }
    }
}

fn test_a() {
    // expands one println per type!
    print_structs! { i8 i16 usize String }
}

fn test_b() {
    // expand using a macro
    apply_macro_to_structs!(print_structs);

}

fn main() {
    test_a();
    test_b();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM