Marketing of D - article topic ideas?
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Jun 6 22:16:35 PDT 2010
On Mon, Jun 7, 2010 at 06:58, Nick Sabalausky <a at a.a> wrote:
> "dsimcha" <dsimcha at yahoo.com> wrote in message
> news:huh892$agk$1 at digitalmars.com...
> >
> > /**Finds the largest element present in any of the ranges passed in.\
> > */
> > CommonType!(staticMap!(ElementType, T)) largestElement(T...)(T args) {
> > // Quick and dirty impl ignoring error checking:
> > typeof(return) ret = args[0].front();
> >
> > foreach(arg; args) {
> > foreach(elem; arg) {
> > ret = max(elem, ret);
> > }
> > }
> >
> > return ret;
> > }
> >
>
> I clearly haven't been following D2 closely enough. Or maybe I'm just more
> tired than I think... Can you explain that function signature?:
> CommonType!(staticMap!(ElementType, T)) largestElement(T...)(T args) {
>
>
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:
say you have T == (int[], byte[], ulong[])
then staticMap!(ElementType, T) is (int,byte,ulong)
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'.
Then, he use typeof(return) to create a variable with this type he just
obtained.
I really like this compile-time calculations on types: as David said, it
allows you to stay generic while having well-defined behavior.
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.
Hmm, in fact it could be put in this example, because it shows this kind of
function can be safe.
Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100607/8bcb4610/attachment.html>
More information about the Digitalmars-d
mailing list