variadic function: passing args

Chris Nicholson-Sauls ibisbasenji at gmail.com
Thu Jul 6 18:01:10 PDT 2006


Kirk McDonald wrote:
> 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.
> 

I've done this same thing before, in ColdC where we have the List Splice Operator '@'. 
Pointless ColdC example:

# public method .pointless(): lock {
#   var args;
#
#   args = [42, "foo", $root];
#   .another(@args);
# }

In this case the method .another() would be called with (42, "foo", $root), as the list 
variable 'args' has been 'spliced' into its arguments list.  I have found it quite useful 
in that platform at least.  Some D analog to this might prove equally useful.  The idea of 
a Tuple datatype also seems potentially promising.  In a sense, a Tuple can be directly 
mapped to a structure, and so can function arguments -- therefore, function arguments can 
be directly mapped to a Tuple, and vice versa.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list