varargs when they're not all the same type?

H. S. Teoh hsteoh at qfbox.info
Fri Mar 15 00:11:32 UTC 2024


On Thu, Mar 14, 2024 at 08:58:21PM +0000, Andy Valencia via Digitalmars-d-learn wrote:
> On Thursday, 14 March 2024 at 18:05:59 UTC, H. S. Teoh wrote:
> > ...
> > The best way to do multi-type varags in D is to use templates:
> > 
> > 	import std;
> > 	void myFunc(Args...)(Args args) {
> 
> Thank you.  The first parenthetical list is of types, is it not?  I
> can't find anywhere which says what "type" is inferred for "Args..."?
> (gdb pretends like "arg" is not a known symbol.)  Is it basically a
> tuple of the suitable type?
[...]

The first set of parenthesis specify compile-time arguments. The
specification `Args...` means "zero or more types".  So it could be any
list of types, which naturally would be chosen according to the
arguments given. For example, to pass an int and a float, you'd do
something like:

	myFunc!(int, float)(123, 3.14159f);

and to pass a string, two ints, and a char, you'd write:

	myFunc!(string, int, int, char)("abc", 123, 456, 'z');

Having to specify types manually, of course, is a lot of unnecessary
typing, since the compiler already knows what the types are based on
what you write in the second pair of parentheses.  For this reason,
typical D code will omit the first pair of parentheses (the `!(...)`,
that is, the compile-time arguments) and just let the compiler infer the
types automatically:

	myFunc(123, 3.14159f); // compiler figures out Args = (int, float)
	myFunc("abc", 123, 456, 'z'); // compiler figures out Args = (string, int, int, char)


T

-- 
A program should be written to model the concepts of the task it performs rather than the physical world or a process because this maximizes the potential for it to be applied to tasks that are conceptually similar and, more important, to tasks that have not yet been conceived. -- Michael B. Allen


More information about the Digitalmars-d-learn mailing list