Conflict between function and template with the same name

Timon Gehr via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 29 03:34:43 PDT 2014


On 06/29/2014 11:31 AM, Rene Zwanenburg wrote:
> On Sunday, 29 June 2014 at 08:52:36 UTC, Uranuz wrote:
>>> import std.stdio;
>>>
>>> string getByName(string name)
>>> {
>>>     return "smth";
>>> }
>>>
>>> template getByName(string name)
>>> {
>>>     enum getByName = .getByName(name);
>>> }
>>>
>>>
>>> void main()
>>> {
>>>     writeln(getByName!("name"));
>>> }
>>
>> Thanks a lot! Very interesting. Do you see any reasoning why this
>> happens?
>
> I think it has to do with variable shadowing. The lookup rules for enums
> are the same as for variables. Since the getByName enum is declared
> inside the template scope it takes precedence over the function in the
> outer scope, even when initializing the enum.
>
> I'm not sure though, hopefully someone a bit more knowledgeable than me
> comes along to clarify.
>
> Prepending a dot makes the lookup happen in global scope.

I think it is either a bug or an unnecessary limitation. The following 
compiles:


string s;
void writeln(T...)(T args){ s~=args[0]; writeln(args[1..$]); }
void writeln(){ s~="\n"; }


string getByName()(string name){
     return "smth";
}
void getByName(){
     pragma(msg, getByName!"foo");
}
template getByName(string name){
     enum getByName = getByName!()(name);
}


void main(){
     pragma(msg,getByName!("name"));
     writeln("123","1234");
}

I.e. calling a different overload from a templated function is 
supported, instantiating a different overload from a function is 
supported, instantiating a different overload from template scope is 
supported, but not calling a different overload from template scope. 
It's probably left out accidentally.


More information about the Digitalmars-d-learn mailing list