Is this correct?

Petar Petar
Thu Feb 6 23:31:39 UTC 2020


On Thursday, 6 February 2020 at 23:05:19 UTC, 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?

It's surprising, but it has to do with how overload sets are 
created.

You can get the "foo string" by using a selective import:

--- foolib.d
import std.stdio;
void foo(string s) { writefln("foo string"); }


--- main.d
import std.stdio;
import foolib : foo;
void foo(const(char)[] s) { writefln("foo const"); }
void main()
{
    foo("hello");
}


Which is essentially equivalent to a private alias:


--- foolib.d
import std.stdio;
void foo(string s) { writefln("foo string"); }


--- main.d
import std.stdio;
import foolib;
private alias foo = foolib.foo;
void foo(const(char)[] s) { writefln("foo const"); }
void main()
{
    foo("hello");
}

The idea is that local symbols must take precedence 
(anti-hijacking principle - adding imports should not change the 
meaning of your code).
Overloading works when all symbols are declared in the same 
scope. For example, if both overloads of foo were in foolib, then 
they would naturally overload (with both normal or selective 
imports).
Adding an alias is essentially creating a symbol in the local 
scope - a "symlink" to another symbol.
So overload a symbol A in scope S1 with symbol B in S2, you need 
to add 'alias A = S2.B' in scope S1.

Cheers,
Petar


More information about the Digitalmars-d mailing list