www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Deducing a template argument from an aliased parameter

reply rcorre <ryan rcorre.net> writes:
In the following example, it seems like the signatures of fun1 
and fun2 should
be equivalent. Both accept a Vector!(T, 2), the only difference 
is that fun2
goes through an alias.

struct Vector(T, int N) { }
alias Vector2(T) = Vector!(T, 2);

void fun1(T)(Vector!(T, 2) vec) { }
void fun2(T)(Vector2!T vec) { }

unittest {
   fun1(Vector!(float, 2).init);
   fun2(Vector!(float, 2).init);
}

Why can fun1 deduce `T`, but fun2 can't?

Failure:
"template d.fun2 cannot deduce function from argument types 
!()(Vector!(float, 2))"?
Dec 31 2015
parent anonymous <anonymous example.com> writes:
On 31.12.2015 23:37, rcorre wrote:
 struct Vector(T, int N) { }
 alias Vector2(T) = Vector!(T, 2);

 void fun1(T)(Vector!(T, 2) vec) { }
 void fun2(T)(Vector2!T vec) { }

 unittest {
    fun1(Vector!(float, 2).init);
    fun2(Vector!(float, 2).init);
 }

 Why can fun1 deduce `T`, but fun2 can't?

 Failure:
 "template d.fun2 cannot deduce function from argument types
 !()(Vector!(float, 2))"?
Vector2 is a little more than just an alias, it's a template for aliases. Your Vector2 is short for this: ---- template Vector2(T) { alias Vector2 = Vector!(T, 2); } ---- You can see that such a template could map different T types to the same result type. For example, Vector2!int and Vector2!long could both become aliases to Vector!(long, 2). Deducing T from a Vector!(long, 2) argument would be ambiguous then. T could be int or long, and there is no way to tell what it should be. That's just how I make sense of this, though. I'm not sure if it's the whole picture.
Jan 01 2016