I have a Component
trait that has a method to return an index, like so:
trait Component {
fn index(&self) -> usize;
}
These indexes are used for setting flags in a bitset. For example, a Component
trait object returning an index of 5 would result in 5th bit being set in a container.
Currently I return a running index for each implementing type manually:
struct Foo;
struct Bar;
impl Component for Foo {
fn index(&self) -> usize { 0 }
}
impl Component for Bar {
fn index(&self) -> usize { 1 }
}
The trait objects are inserted into a container which keeps track of added components using a bitset:
struct Container<'a> {
components: Vec<Component + 'a>,
bits: BitSet
}
impl<'a> Container<'a> {
fn add<T: Component + 'a>(&mut self, component: T) {
self.components.push(component);
self.bits.set(component.index());
}
}
This works fine, but manually returning the index for each implementing type is cumbersome. How could I make it so that each implementing type would get its index automatically?