Idea: extend typesafe variadic functions
Daniel Keep
daniel.keep.lists at gmail.com
Sat Mar 31 21:49:53 PDT 2007
Jarrett Billingsley wrote:
> One of the "cool features you probably didn't know about" with typesafe
> variadic functions is that you can make a variadic class parameter which
> will be constructed with the parameters to the function, like so:
>
> class A
> {
> this(int x, float y){}
> }
>
> void func(A a...)
> {
>
> }
>
> ....
>
> func(3, 4.5);
>
> This will implicitly call the constructor for A when you call func() and
> will forward those parameters to the class constructor.
*Boggle* When did *that* happen?!
> What would be really cool is to have this happen for an array of classes or
> structs as well:
>
> class A
> {
> this(int x) {}
> this(float x) {}
> this(char[] s) {}
> }
>
> void func(A[] args...)
> {
>
> }
>
> ....
>
> func(1, 2.3, "hi");
>
> Right now, it says "cannot implicitly convert 1 to A" or something, but with
> this new feature, this would construct three instances of A, one using the
> int constructor, one using the float, and one using the string. Of course,
> for sanity's sake, it would only try to construct As using single-parameter
> constructors.
>
> This would work similarly for structs:
>
> struct S
> {
> static S opCall(T)(T value)
> {
> S s;
> return s;
> }
> }
>
> void func(S[] args...)
> {
>
> }
>
> ....
>
> func(1, 2.3, "hi");
>
> (See if you can figure out why I think this would be cool.. ;) )
I'm afraid I can't :(
I imagine that there's probably some very nice things you could do with
this, but I can't see why you couldn't do it already:
void funcT(Ts...)(Ts args)
{
A[] as;
as.length = args.length;
foreach( i, arg ; args )
as[i] = new A(arg);
func(as);
}
Getting this to work with overloads would be... interesting, but
certainly doable. Heck, you could probably turn the above into a
generic templated "array-of-T" initializer.
On a side note, am I the only one who is *really* uncomfortable with the
fact that the first example works at all? :S
-- Daniel
--
int getRandomNumber()
{
return 4; // chosen by fair dice roll.
// guaranteed to be random.
}
http://xkcd.com/
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
More information about the Digitalmars-d
mailing list