templating operators

Brad Roberts braddr at puremagic.com
Thu Mar 2 18:01:07 PST 2006


I'm trying to create a container that will allow arbitrary key/value pair 
trees.  Box seems like a great start at supporting a 'holds anything' 
container.  The next step is making a smooth associative array of them.  
However, I don't seem to be able to create a nice templated opIndex or 
opIndexAssign.

-------- test.d ---------
import std.stdio;
import std.boxer;

class ValueContainer
{
    Box[char[]] _objects;

    template opIndex(T)
    {   
        T opIndex(char[] key)
        {   
            return unbox!(T)(_objects[key]);
        }
    }

    int opIndexAssign(int newValue, char[] key)
    {   
        _objects[key] = box(newValue);
        return 0;
    }

    template getValue(T)
    {   
        T getValue(char[] key)
        {   
            return unbox!(T)(_objects[key]);
        }
    }

    template insertKeyAndValue(T)
    {   
        void insertKeyAndValue(char[] key, T newValue)
        {   
            _objects[key] = box(newValue);
        }
    }
}

int main()
{
    ValueContainer values = new ValueContainer();

    values["int"] = 1;
    values.insertKeyAndValue!(int)("key", 10);

    writef("int: %s\n", values["int"]);
    writef("key: %s\n", values["key"]);
    writef("key: %s\n", values.getValue!(int)("key"));

    return 0;
}
---------------

$ dmd -g test.d                                                 
test.d(46): no [] operator overload for type test.ValueContainer
test.d(47): no [] operator overload for type test.ValueContainer
test.d(48): function expected before (), not 0 of type int

Any thoughts on how to make this work well?

Thanks,
Brad



More information about the Digitalmars-d mailing list