How to tell Rust to provide blanket implementations only when all trait requirements are met, not any of them

Super short example. This generates a conflicting requirement error, but I want Rust to be able to tell between the types that implement all of the trait requirements. Is it possible?

trait A {
    fn foo();
}

trait B {}

trait CM {}

trait DM {}

impl<T> A for T
where T : CM + B
{
    fn foo() {

    }
}

impl<T> A for T
where T : DM + B
{
    fn foo() {
    }
}

fn main() {}
trait A {
    fn foo();
}

trait CM {}
trait DM {}

impl<T> A for T
where T : CM
{
    fn foo() {}
}

impl<T> A for T
where T : DM
{
    fn foo() {}
}

fn main() {}

This generates a conflicting requirement too, so I guess what I want to do is impossible? I want to provide implementation only for part of the types, namely those types that implement a certain trait (or even better, all of the specified traits).

In the second post there might be some type that implemented both traits, which would lead to ambiguity. I guess the same reasoning applies to my first post. Well, then how do I achieve what I want? I need to specialize the implementation.

It's a lot clumsier but just might be good enough depending on your use case, you could create newtypes and implement the trait for them instead:

struct CWrapper<T: CM + B>(T);

struct DWrapper<T: DM + B>(T);

impl<T: CM + B> A for CWrapper<T> {
    fn foo() {
        println!("C");
    }
}

impl<T: DM + B> A for DWrapper<T> {
    fn foo() {
        println!("D");
    }
}

I think doing it through a blanket implementation might be impossible due to the ambiguity issue you mentioned.

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.