Combining variadic functions with class templates
Philippe Sigaud
philippe.sigaud at gmail.com
Thu Sep 30 12:17:39 PDT 2010
>> Thanks, that works, but that syntax seems a little verbose to me. Is the
>> first syntax generally not supported in D?
>>
>
> It is not. You can use auto v = Vec3f(1,1,1);
If you use a creation function, types and length are deduced
automatically, there is no need to indicate them to the compiler.
Let's add some sugar on top, it complexifies the signature a bit but
makes creating a vector a pleasure:
import std.traits;
auto vector(Ts...)(Ts values) if (!is(CommonType!(Ts) == void))
{
return Vector!( CommonType!(Ts), Ts.length)(values);
}
(CommonType: http://digitalmars.com/d/2.0/phobos/std_traits.html#CommonType)
usage:
auto v1 = vector(1,2,3); // v1 is a Vector!(int,3)
auto v2 = vector(1.5); // v2 is a Vector!(double, 1)
auto v3 = vector(1,2, 3.1415, 2.71828); // v3 is a Vector!(double, 4):
CommonType!(int,int,double,double) is double
auto v4 = vector('a','b'); // Vector!(char,2)
auto v5 = vector("abc", 3); // Compile-time error, impossible vector.
Philippe
More information about the Digitalmars-d-learn
mailing list