Disambiguation of a call to an overloaded function when the argument satisfies multiple signatures?
I have a reader class that calls
write_string()
via reader.write_to()
which is different depending on if the write implements a Writer or StringWriter trait.
I want to set up my reader.write_to() function to call either one depending on what the writer implements. Ideally, i'd like W to be io.Writer
OR io.StringWriter
but for now I overloaded the function.
When I call reader.write_to()
with a writer that implements both traits, I get an error
ambiguous call to 'write_to', each candidate requires 0 implicit conversions, disambiguate with an explicit cast
Makes sense, but does anyone know how I can make it explicit which function I'm calling? Or how I could reorganize the code so the function call is not vague? I'm new to traits/interfaces for the most part, so any help would be appreciated!6 Replies
Interesting use-case. One way to address it is to implement another overload that requires W to be both Writer AND StringWriter. This should be (but I'm not sure if the compiler does this yet) considered more-specific than either of the other conversions, so it should resolve the ambiguity
It'd be great to give this approach a try - if the compiler doesn't consider it to be more-specific then please file a bug 🙂
Related question here: https://ptb.discord.com/channels/1087530497313357884/1211039561786859590
Just to confirm, is StringWriter a subtrait of the Writer? If so, then compiler should be able to reason about it and if not it's a bug.
StringWriter and Writer are two separate traits in this case.
For my use case, structs that implement StringWriter don't necessarily need to implement Writer as well (even though they usually do)
So in that case, Chris's suggestion is the answer.
Thanks! I’ll give it a go