Type-safe search for a type implementing a trait in a list?

It's pretty easy to implement a trait on a tuple if all elements implement the trait:

impl<A: Trait, B: Trait> Trait for (A, B) { ... }

But the disjunctive version, where a trait is implemented on a tuple if any of the parts have the trait, is not so easy, as this will cause a coherence error:

impl<A: Trait, B> Trait for (A, B) { ... }
impl<A, B: Trait> Trait for (A, B) { ... }

I want to implement a mechanism such that given a tuple of "listeners" for different events, we can call a function on the tuple and the appropriate listener will be called. Each event listener is a trait, and if we could write the above code, then the impls would dispatch the event to the appropriate element of the tuple. (I don't mind rejecting types where multiple types implement the event listener, or choosing arbitrarily in that case.)

Unfortunately you can't do this. I recommend declaring that the implementer of the trait should always be first in the tuple. (or second)

That would work if there was only one event, but the second event can't make the same promise, right? In particular, I want the set of events to be dynamically extensible, so different events can't know which other events have been declared in the list.

In that case, I recommend having all entries always implement the trait, with a function that may return None or something like that.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.