Domanda

T maybe(alias nullCheck, T)(T expr, T def)
{
    if (nullCheck(expr))
    {
        return def;
    }
    else
    {
        return expr;
    }
}

auto tokens = chomp(readln())
              .toLower()
              .split()
              .maybe!(a => a.empty)([""])

When the template arguments to maybe are arranged with the alias coming first, the compiler is correctly able to infer the argument types. However, when the template arguments are switched such that T comes first, it cannot infer them, and will not compile. Why is this?

È stato utile?

Soluzione

It's because template arguments are after all positional arguments. If nullCheck was the second argument, you would have to specify T first before you could specify nullCheck.

The compiler can (informally) only try to infer the arguments to the right of the last positional argument, much like if they were default arguments.

Note this is the same as in C++ and reasonable if you think about it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top