Is this correct?

Steven Schveighoffer schveiguy at gmail.com
Thu Feb 6 23:22:55 UTC 2020


On 2/6/20 6:05 PM, Jonathan Marler wrote:
> The named arguments DIP got to question what this example would do:
> 
> --- foolib.d
> import std.stdio;
> void foo(string s) { writefln("foo string"); }
> 
> 
> --- main.d
> import std.stdio;
> import foolib;
> void foo(const(char)[] s) { writefln("foo const"); }
> void main()
> {
>     foo("hello");
> }
> 
> 
> This prints "foo const".  And if you move the function overload from 
> foolib.d to main.d, it will print "foo string".  Is this the expected 
> behavior?
> 

Yes. Overloads sets are delineated by scope, from inner to outer. All 
imported modules count as a further outer scope. See information here: 
https://dlang.org/spec/function.html#overload-sets

In order to bring imported symbols into your overload set, you need to 
alias them. Also you could selectively import the symbol to get it into 
the module's namespace.

--- main.d

import std.stdio;
import foolib;
alias foo = foolib.foo; // this or import foolib: foo;
void foo(const(char)[] s) { writefln("foo const"); }

void main()
{
    foo("hello");
}

---

prints foo string


As a demonstration to realize it stops at your module's scope, change 
the local foo to accept an int (and don't alias in the external foo), 
and you will get an error even though foolib.foo could accept the parameter.

-Steve


More information about the Digitalmars-d mailing list