variadic function: passing args

Kirk McDonald kirklin.mcdonald at gmail.com
Thu Jul 6 16:29:11 PDT 2006


pragma wrote:
> In article <e8jemv$2pfh$1 at digitaldaemon.com>, Ivan Senji says...
> 
>>Nice idea, IMO the compiler should do this for us, but it would be even
>>nicer if we could do something like:
>>
>>blah = foo(...[0..5]); //Pass to foo only the first five arguments
> 
> 
> I agree, although I don't like the idea of using "..." explicitly as an
> identifier.  I'd rather see a variation of the "named vararg" syntax like so:
> 
> void foo(args ...){
> writefln("hello world",args);
> }
> 
> The only problem with the above case is: what type does 'args' actually have (or
> in Ivan's example, what type does '...' have)?  
> 
> It could be considered an error to use the "vararg expression" in any context
> other than as a function argument or parameter, but I can't help but think that
> it would open up a whole world of expressions if it were a proper type unto
> itself.
> 
> - EricAnderton at yahoo

Well, the answer is obvious: It is a tuple. We are essentially 
discussing the equivalent of this Python code:

def func(*args): # packs function arguments into a tuple
     print args

def main():
     a = ("blah", 50, 200.35) # creates a tuple
     func(1, 2, 3, "apple", 5.0) # call the function with normal args
     func(*a) # "unpack" the tuple, call the func with it

 >>> main()
(1, 2, 3, "apple", 5.0)
("blah", 50, 200.35)

Though I'm not sure going quite as far as Python does with tuples is 
what we'd want for D. However, a proper built-in tuple type would be 
/damnably/ useful.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://dsource.org/projects/pyd/wiki



More information about the Digitalmars-d mailing list