ModularM
Modular2y ago
7 replies
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)


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:
    ...


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!
Was this page helpful?