Parameters declared as the alias of a template won't accept the arguments of the same type.

Ali Çehreli acehreli at yahoo.com
Mon May 2 20:08:48 UTC 2022


On 5/2/22 12:17, Stanislav Blinov wrote:
 > On Monday, 2 May 2022 at 16:29:05 UTC, Loara wrote:
 >
 >> Template deduction for aliased function parameter is a very tricky
 >> argument and it's not so simple to handle in certain cases. Consider
 >> for example this code:
 >>
 >> ```d
 >>     template MyAlias(T){
 >>       alias MyAlias = int;
 >>     }
 >>
 >>     T simp(T)(MyAlias!T val){
 >>       return T.init;
 >>     }
 >>
 >>     int main(){
 >>       simp(3);//Impossible to deduce T
 >
 > Why? That's the issue. It is very possible to deduce T here. Compiler
 > just isn't trying.

That's fine because D does not promise to solve such problems. It 
follows simple deduction rules.

 > The function takes an int.

How would the solution be? Wouldn't the compiler have to parse all 
accessible template bodies to figure out which ones fit? Imagine the 
following two other templates:

template YourAlias(T) {
   alias YourAlias = int;  // Is it this one?
}

template HerAlias(T) {
   // ...
   alias HerAlias = HisAlias!SomeNameInThisScope;  // Or thi?
}

The compiler would have to solve this problem by digging into HisAlias's 
SomeNameInThisScope instantiation as well. As far as know, the D 
language does not work that way. Prolog and friends perhaps?

 > Doesn't take a rocket
 > scientist to figure that one out.

I think this is one of those cases where it is easier for a human. 
Although, I think I would have difficulty if there were more than one 
template parameter.

 > I might as well forego the templates and
 > just write explicit overloads. At which point I would question why use
 > templates at all.

Templates allow single implementations to work for many types, manifest 
constants, aliases, etc. I wouldn't want to write (or mix-in?) sort() 
for MyType. Templates are wonderful and their implementation in D is 
refreshing.

Ali



More information about the Digitalmars-d-learn mailing list