作者:mobiledu2502874643 | 来源:互联网 | 2022-12-09 12:23
我有一个Component
特征,该特征具有返回索引的方法,如下所示:
trait Component {
fn index(&self) -> usize;
}
这些索引用于在位集中设置标志。例如,Component
返回索引为5 的特征对象将导致在容器中设置第5位。
目前,我为每种实现类型手动返回运行索引:
struct Foo;
struct Bar;
impl Component for Foo {
fn index(&self) -> usize { 0 }
}
impl Component for Bar {
fn index(&self) -> usize { 1 }
}
特质对象插入到容器中,该容器使用位集跟踪添加的组件:
struct Container<'a> {
components: Vec,
bits: BitSet
}
impl<'a> Container<'a> {
fn add(&mut self, component: T) {
self.components.push(component);
self.bits.set(component.index());
}
}
这可以正常工作,但是手动返回每种实现类型的索引很麻烦。我怎样才能使每种实现类型都自动获得其索引?
1> Peter Hall..:
您可以定义一个可递归调用的宏:
macro_rules! impl_component {
// Empty case to end the recursion
($n:expr ;) => {};
// Match the current count, the current type, and whatever else comes after
($n:expr ; $t:ty $(, $rest:tt)*) => {
impl Component for $t {
fn index(&self) -> usize { $n }
}
// Recurse, incrementing counter and only passing the remaining params
impl_component!($n + 1; $($rest),*);
};
// For the first recursion, set the counter initial value to zero
($($types:tt),+) => { impl_component!(0; $($types),*); };
}
impl_component!(Foo, Bar, Baz);
生成的代码将包括以下实现:
impl Component for Baz {
fn index(&self) -> usize { 0 + 1 + 1 }
}
编译器会将这些表达式折叠成文字,因此结果等于您想要的结果。