Some more template syntax sugar

Reiner Pope reiner.pope at REMOVE.THIS.gmail.com
Mon Aug 28 05:18:04 PDT 2006


I think function templates still require too much in the way of type 
annotations. Take the canonical example, sqr:

T sqr(T) (T x)
{
	return x*x;
}

In this example, we have to declare T three times, even though I think 
this could be inferred. I propose an alternative syntax:

auto sqr(x)
{
	return x*x;
}

which IMHO looks very elegant.

Here are the rules more formally:
  - if a type is missing for an parameter, template this function by 
that argument. Do this for every parameter.
  - use type inference (just like auto) to determine the return type, 
unless it is marked 'void'

so, the above code becomes:

typeof(__ret) sqr(__t1) ( __t1 x)
{
	auto __ret = x * x;
	return __ret;
}

and for more complex examples,

auto foo(a, b, c, d)
{
	...
}

becomes:

typeof(__ret) foo(__t1, __t2, __t3, __t4) ( __t1 a, __t2 b, __t3 c, __t4 d)
{
	...
}

and the instantiation rules are as per normal.

Cheers,

Reiner



More information about the Digitalmars-d mailing list