On Wednesday, 27 June 2018 at 16:19:56 UTC, Luka Aleksic wrote:
[…]
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."]

Changing the offending line to:

pair!(char, uint) p1 = pair!(char, uint)('a', 1);

fixes the issue.

However I am interested to know why the first code couldn't deduce the types-- and why does it even have to try to deduce them, when I explicitly stated that p1 was of the type "pair of char and uint"?

Thanks,
L. Aleksic

Type inference does not work for struct construction. There are some technical problems with allowing that, such as this() having the capability of being a separate template itself. Relevant issue tracker entry: https://issues.dlang.org/show_bug.cgi?id=6082

Your construction call does not work because the right hand side determines its type using only information present on the right hand side, in that sense you're not explicitly providing types at all.

In order to still be able to make concise construction calls, you can define a factory function:

struct Pair(A, B)
{
    A a;
    B b;

    this(A a, B b)
    {
        this.a = a;
        this.b = b;
    }
}

Pair!(A, B) pair(A, B)(A a, B b)
{
    return Pair!(A, B)(a, b);
}

void main()
{
    auto p = pair(1, "test");
    pragma(msg, typeof(p)); //Pair!(int, string)
}

Reply via email to