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 20:36:31 UTC 2022
On Monday, 2 May 2022 at 20:08:48 UTC, Ali Çehreli wrote:
> 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.
Words, dear guru. Words have a meaning. It is very possible to
deduce here (note the premise). D just isn't trying. That's what
I said. You can say "it doesn't promise". Doesn't exactly change
the meaning, does it? :)
> > 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?
Err... yes? That's what it *is* doing already, for all templates.
> 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?
> }
No. HerAlias and YourAlias are different symbols.
> 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?
Nope. MyAlias is an alias. A template alias, but an alias
nonetheless. It should be resolved prior to trying the overloads.
> > 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.
That's what we have compilers for.
> > 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.
It is, until is isn't. Question du jeour is one of those.
More information about the Digitalmars-d-learn
mailing list