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

Stanislav Blinov stanislav.blinov at gmail.com
Mon May 2 19:17:19 UTC 2022


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. The function takes an int. Doesn't 
take a rocket scientist to figure that one out.

>       simp( cast(MyAlias!string) 4);//Also invalid since 
> MyAlias!string is exactly int

Yes, invalid, as well it should be.

>       simp!string(4);//Ok, no parameter deduction
>     }
> ```

No issue here.

> Instead to use aliases it's better (both in D and in C++) to 
> use constraints/concepts.

No. It *would* be better if compiler didn't play stupid here. I 
shouldn't have to write 50+ more lines boilerplate for what the 
compiler should be able to figure out. I might as well forego the 
templates and just write explicit overloads. At which point I 
would question why use templates at all.




More information about the Digitalmars-d-learn mailing list