alias overloaded function template

Basile Burg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 11 21:37:19 PST 2014


On Tuesday, 11 November 2014 at 19:36:12 UTC, Lemonfiend wrote:
> D is fine with alias this overloaded function:
> ---
> void foo(int t) {}
> void foo(int t, int i) {}
>
> alias bar = foo;
> ---
>
> But isn't as happy aliasing these function templates:
> ---
> void foo(T)(T t) {}
> void foo(T)(T t, int i) {}
>
> alias bar = foo!int;
> ---
>
> Is there some way/other syntax to make an alias like this work? 
> Or specify in the alias which function template to use (ie. 
> alias bar = foo!int(int)).

The problem is not the alias. The error message is about using 
the same identifier for two different things:

> C:\...\temp_0186F968.d(13,1): Error: declaration foo(T)(T t, 
> int i) is already defined.

1/ ===================================================

What you seem to forget is that the declarations:
---------------------
void foo(T)(T t) {}
void foo(T)(T t, int i) {}
---------------------
are actually a two **Eponymous template** with the same name:
---------------------
template foo(T){
     void foo(T t) {}
}
template foo(T){
     void foo(T t, int i) {}
}
---------------------
This produces the same error message:
> C:\...\temp_0186F968.d(13,1): Error: declaration foo(T)(T t, 
> int i) is already defined.

2/ ===================================================

You can make it working by renaming the template name anf by 
grouping the members:
---------------------
template hip(T)
{
     void bud(T t) {}
     void bud(T t, int i) {}
}

alias baz = hip!int.bud;
writeln(typeof(baz).stringof);
// > void(int t) or void(int t, int i) if you invert bud order.
---------------------


More information about the Digitalmars-d-learn mailing list