Struct template cannot deduce function from argument types
H. S. Teoh
hsteoh at quickfur.ath.cx
Wed Jun 27 17:07:54 UTC 2018
On Wed, Jun 27, 2018 at 04:19:56PM +0000, Luka Aleksic via Digitalmars-d-learn wrote:
[...]
> struct pair(T, U) {
> T first;
> U second;
>
> this(T arg_first, U arg_second) {
> first = arg_first;
> second = arg_second;
> }
> };
>
> void main() {
>
> pair!(char, uint) p1 = pair('a', 1);
The usual way I'd write this is:
auto p1 = pair!(char, uint)('a', 1);
This saves having to retype a complicated type, and also gives the
compiler the template arguments in the place where it needs them.
[...]
> I am getting the following error:
>
> scratch.d(14): Error: struct scratch.pair cannot deduce function from
> argument types !()(char, int), candidates are:
> scratch.d(2): scratch.pair(T, U)
> Failed: ["/usr/bin/dmd", "-v", "-o-", "scratch.d", "-I."]
The reason is that the compiler runs semantic on the right-hand side of
the assignment first, before it looks at the type of p1. The expression
`pair('a', 1)` is ambiguous, since the compiler doesn't (yet) know which
instantiation of `pair` you intended.
Writing it the way I recommend above avoids this problem.
T
--
Answer: Because it breaks the logical sequence of discussion.
Question: Why is top posting bad?
More information about the Digitalmars-d-learn
mailing list