anonymous templates, and access control / connection with static class

Bill Baxter dnewsgroup at billbaxter.com
Tue Oct 17 23:47:49 PDT 2006


I really like the idea of being able to define a set of template 
parameters that all go together in one place like:

template ArrayStuff(ArrayT)
{
    alias typeof(ArrayT[0]) ElemT;  // used by several functions--handy!

    ElemT get_item(ArrayT a, int i) {
      ...
    }
    void set_item(ArrayT a, int i, ElemT v) {
    ...
    }
}

But I find myself really reluctant to do that simply because then to use 
it I'll have to say
    ArrayStuf!(ArrayT).get_item(a,3);
or make an alias for every single thing in there, at which point the 
convenience of one-stop shopping for defining the common things is negated.

So what about allowing anonymous templates?  It would be like this:

template (ArrayT)
{
    alias typeof(ArrayT[0]) ElemT;
    ElemT get_item(ArrayT a, int i) {
      ...
    }
    void set_item(ArrayT a, int i, ElemT v) {
    ...
    }
}

Basically it would be just like the current single-function rule, but 
apply the transformation to all the functions.  That is, it would the 
following direct calls possible:
    get_item!(int[])(a, i)
    set_item!(int[])(a, i, 5)

The ElemT alias itself is problematic...  Not sure what should be done 
about that.  In this case I would like it to be hidden from the outside 
world, but I can imagine other cases where you would want to make it 
public.  Sometimes determining derived types can be a lot of work, so it 
would be nice if I could use ElemT!(int[]) to get int from int[].  (Ok, 
maybe there's better ways in this case but in general...)

In any event, I think access control for the things in a template would 
be nice.  There's a lot in common with an all static-class there, so it 
would make sense (and again be nice and consistent) if I could label 
things 'private' and 'public' inside a template.  In fact an all-static 
templated class and a template are pretty much identical.

In fact is there any difference at all between these two?:

template ArrayStuff(ArrayT) {
    alias typeof(ArrayT[0]) ElemT;
    ElemT get_item(ArrayT a, int i) { ... }
    void set_item(ArrayT a, int i, ElemT v) { ... }
}

class ArrayStuff(ArrayT) {
    alias typeof(ArrayT[0]) ElemT;
    static ElemT get_item(ArrayT a, int i) { ... }
    static void set_item(ArrayT a, int i, ElemT v) { ... }
}


--bb



More information about the Digitalmars-d mailing list