Internal templates

Part of TemplatesCategory

Description

Shows how templates within classes can be useful.

Example

// by Joey Peters

/*
This should show you how templates in classes are useful and how they
could (or should) be used with mixins.

Practicly, this is mostly useful for when you're writing your own containers.
*/

class List(T) {
public:
    // hold an array with items
    T[] data;
    this() {}
    // constructs with data set
    this(T[] d) {
        data = d;
    }
    // convert the array automatically, but still allow it's functionality.

    template as(NT) {
        // copy completely copies an array, but with a new type
        NT[] copy() {
            NT[] ret;
            foreach(T i; data) {
                ret.length = ret.length + 1;
                // cast it to the new type
                ret[ret.length - 1] = cast(NT) i;
            }
            return ret; 
        }
    }
    // mix in it's own type, so the functionality is still there for

    // it's own type.
    mixin as!(T);
}

void main() {
    // first, we have two types of lists, integer lists and double lists
    alias List!(int) iList;
    alias List!(double) dList;
    // then, we make an integer list

    iList list1 = new iList;
    // list 2 is a copy of list 1
    iList list2 = new iList(list1.copy());
    // list 3 is a double list, and a copy of list 2
    dList list3 = new dList(list2.as!(double).copy());
    // magic :) you may want to overload a few things to make this look more elegant etc.

    return;
}

Comments

There's been some discussion in a newsgroup about where this code is legal code (it might violate the D specification). I don't know whether it's allowed or not. So it might be a good idea to use caution when using this code. I've pasted some of the newsgroup comments below -- Justin Calvarese


From digitalmars.D.announce:2201:

Is that not incorrect? The spec clearly states (http://www.digitalmars.com/d/template.html) that "Templates cannot be used to add non-static members" to classes. This is precisely what that example does, and the funny thing is that it compiles and runs ok. I don't see how that can work, unless the compiler is treating the templated method as final.


From digitalmars.D.announce:2206:

That is incorrect. Though I think templates can not add virtual members to classes (ie. I believe template methods are implicitly final). Though I have not tested this to be sure.


From digitalmars.D.announce:2207:

Though the spec says a mixin *can* add virtual functions to a class. That said, I recently encountered a problem whereby a class method refused to override the templated version.


From digitalmars.D.announce:2211:

I expanded that example a bit to use inheritance and it looks like the documentation is wrong... Not only are the functions non-static and non-final but are (correctly) virtual as well.


Source

Posted by Anonymous
Date/Time Fri Sep 10, 2004 12:03 pm