M
Modular•7mo ago
toasty

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.
fn write_string[W: Writer](inout writer: W, string: String) raises -> Int:
return writer.write(string.as_bytes())

fn write_string[W: StringWriter](inout writer: W, string: String) raises -> Int:
return writer.write_string(string)
fn write_string[W: Writer](inout writer: W, string: String) raises -> Int:
return writer.write(string.as_bytes())

fn write_string[W: StringWriter](inout writer: W, string: String) raises -> Int:
return writer.write_string(string)
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.
fn write_to[W: io.Writer](inout self, inout writer: W) raises -> Int64:
...

fn write_to[W: io.StringWriter](inout self, inout writer: W) raises -> Int64:
...
fn write_to[W: io.Writer](inout self, inout writer: W) raises -> Int64:
...

fn write_to[W: io.StringWriter](inout self, inout writer: W) raises -> Int64:
...
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
Chris Lattner
Chris Lattner•7mo ago
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 🙂
Ehsan M. Kermani (Modular)
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.
toasty
toasty•7mo ago
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)
Ehsan M. Kermani (Modular)
So in that case, Chris's suggestion is the answer.
toasty
toasty•7mo ago
Thanks! I’ll give it a go
Want results from more Discord servers?
Add your server