This is a simple template example showing a class that takes a type parameter and behaves like an array of that type:
Source:
Expand


namespace Template is
    use System.Exception;

    class Main is
        void init() is
            // MyArray<String> is a specialization of MyArray<T> with String substituted
            // for T wherever it appears in MyArray
            var a = new MyArray<String>(10);

            foreach var i; 0..a.Length-1 do
                IO.Std.out.println( "set element " + i + "..." );
                a[i] = i.toString();
            od

            IO.Std.out.println( "result: " + a );
        si      
    si

    // this is a template class with a type parameter T
    // it wraps an array of element type T and provides index accessor 
    // methods (get T[int] and set T[int]) that allow objects of the resulting
    // type to be accessed using array subscript syntax.
    class MyArray<T> is
        T[] values;

        void init( int length ) is
            values = new T[length];
        si

        get int Length is
            return values.length;
        si

        set T[int index] = v is
            values[index] = v;
        si

        get T[int index] is
            return values[index];
        si

        String toString() is
            return Class.Name + "(" + values.toString() + ")";
        si
    si
si
Output:
Expand
set element 0...
set element 1...
set element 2...
set element 3...
set element 4...
set element 5...
set element 6...
set element 7...
set element 8...
set element 9...
result: LSPPage.P_21679_18.Template.MyArray<System.String>(0,1,2,3,4,5,6,7,8,9)
site design and content copyright (C) jeek 1995-2010     [ 13132 ]