Annoying thing about auto ref function template

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 20 13:20:52 PDT 2017


On Monday, March 20, 2017 19:49:03 Yuxuan Shui via Digitalmars-d wrote:
> An auto ref function template should behave like a normal
> function template, but it doesn't.
>
> You can fully instantiate a function template by specifying all
> of its template parameters, but you can't do that with auto ref
> templates. The only way to instantiate an auto ref template is to
> call it.
>
> This makes auto ref an outlier. Because you get a function by
> instantiate function template, you can pass the result as
> template alias argument, and you can create alias of the
> resulting function. And you can't do that with an auto ref
> template, which makes them quite annoying.
>
> I wonder why is auto ref designed this way? And can we change
> this?

Well, you can explicitly instantiate it and call it at the same time, it
does work. When it doesn't work is when you just try and instantiate it
without calling it. And the reason is because the refness is inferred from
the function argument. If the argument is an lvalue, then the parameter is
inferred as ref, whereas if it's an rvalue, it's inferred as non-ref. The
refness is not actually part of the type, because ref is not a type
qualifier. As such, AFAIK, the language simply has no way to pass the
refness as part of the explicit instantiation. In something like

auto foo(T)(auto ref T t)
{
    ...
}

the T in the template parameters has nothing to do with the ref, and in
fact, you could have something like

auto foo(T)(auto ref T t1, auto ref T t2)
{
    ...
}

and end up with t1 being ref and t2 being non-ref (or vice versa or both ref
or neithe ref). So, the refness would need to somehow be indicated
separately from the template argument, and I have no idea what that would
even look like.

So, yes, this particular restriction can be annoying, but there is a good
reason for the restriction (though the error message _is_ pretty bad), and I
have no idea how we would fix the problem.

- Jonathan M Davis



More information about the Digitalmars-d mailing list