是否可以创建一个宏来计算扩展项的数量? [英] Is it possible to create a macro which counts the number of expanded items?

查看:54
本文介绍了是否可以创建一个宏来计算扩展项的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个宏来计算扩展项的数量?

Is it possible to create a macro which counts the number of expanded items?

macro_rules! count {
    ($($name:ident),*) => {
        pub enum Count {
           $(
               $name = 1 << $i // $i is the current expansion index
            ),*
        }
    }
}

count!(A, B, C);

推荐答案

下面是一个宏,用于计算匹配项的数量:

Here is a macro that counts the number of matched items:

macro_rules! count_items {
    ($name:ident) => { 1 };
    ($first:ident, $($rest:ident),*) => {
        1 + count_items!($($rest),*)
    }
}

fn main() {
    const X: usize = count_items!(a);
    const Y: usize = count_items!(a, b);
    const Z: usize = count_items!(a, b, c);
    assert_eq!(1, X);
    assert_eq!(2, Y);
    assert_eq!(3, Z);
}

请注意,计数是在编译时计算的.

Note that the counting is computed at compile time.

以您的示例为例,您可以使用累积 a>:

For your example, you can do it using accumulation:

macro_rules! count {
    ($first:ident, $($rest:ident),*) => (
        count!($($rest),+ ; 0; $first = 0)
    );
    ($cur:ident, $($rest:ident),* ; $last_index: expr ; $($var:ident = $index:expr)+) => (
        count!($($rest),* ; $last_index + 1; $($var = $index)* $cur = $last_index + 1)
    );
    ($cur:ident; $last_index:expr ; $($var:ident = $index:expr)+) => (
        #[repr(C)]
        enum Count {
            $($var = 1 << $index),*,
            $cur = 1 << ($last_index + 1),
        }
    );
}

pub fn main() {
    count!(A, B, C, D);
    assert_eq!(1, Count::A as usize);
    assert_eq!(2, Count::B as usize);
    assert_eq!(4, Count::C as usize);
    assert_eq!(8, Count::D as usize);
}

这篇关于是否可以创建一个宏来计算扩展项的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆