<div class="gmail_quote">On Mon, Jun 7, 2010 at 06:58, Nick Sabalausky <span dir="ltr"><a@a.a></span> wrote:<br><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
"dsimcha" <<a href="mailto:dsimcha@yahoo.com">dsimcha@yahoo.com</a>> wrote in message<br>
news:huh892$agk$1@digitalmars.com...<br>
<div class="im">><br>
> /**Finds the largest element present in any of the ranges passed in.\<br>
> */<br>
> CommonType!(staticMap!(ElementType, T)) largestElement(T...)(T args) {<br>
> // Quick and dirty impl ignoring error checking:<br>
> typeof(return) ret = args[0].front();<br>
><br>
> foreach(arg; args) {<br>
> foreach(elem; arg) {<br>
> ret = max(elem, ret);<br>
> }<br>
> }<br>
><br>
> return ret;<br>
> }<br>
><br>
<br>
</div>I clearly haven't been following D2 closely enough. Or maybe I'm just more<br>
tired than I think... Can you explain that function signature?:<br>
<div class="im">CommonType!(staticMap!(ElementType, T)) largestElement(T...)(T args) {<br><br></div></blockquote><div><br>T is a typetuple, with ranges as elements (types). These ranges may have different element types. staticMap!(ElementType, T) will map the ElementType template on each type in T and from this typetuple create another typetuple:the application of ElementType on each of them:<br>
<br>say you have T == (int[], byte[], ulong[])<br><br>then staticMap!(ElementType, T) is (int,byte,ulong)<br><br>Then, CommonType is a template that takes a typetuple and finds the common type among them. Then any element from any of the input ranges can be cast to this type. If CommonType finds no common type, it returns 'void'.<br>
Then, he use typeof(return) to create a variable with this type he just obtained.<br><br>I really like this compile-time calculations on types: as David said, it allows you to stay generic while having well-defined behavior.<br>
Of course, in a real application, you would put a constraint on this template, testing for CommonType not to be void. That way, calling largest element on (string[], double[][]) wouldn't even compile.<br><br><br>Hmm, in fact it could be put in this example, because it shows this kind of function can be safe.<br>
<br><br>Philippe<br><br></div></div>