Robustness of the built in associative array

Wolfgang Draxinger wdraxinger at darkstargames.de
Tue Mar 28 15:50:48 PST 2006


Nick wrote:

> I think the STL containers do a very good job at being both flexible and
> usable, covering most normal cases of use. The thing missing from D to
> make a STL-like library would be the reference return type.

Well, there's just the little problem, that C++ '&' reference types being
results of functions are not safe either. A C++ reference is IMHO nothing
better than a strongly typed pointer.

example

class foo
{
foo(int bar) { a = new int[bar]; }
int *a;

// ignore the possible bounds error ;-)
int & operator [] (int i){ return a[i]; }

int & something ()
{
        int hello = 123;
        return hello;
}

};

This isn't a bit better than using a pointer instead a reference.

The real problem currently is, that the index expression can be used as a
lvalue, but using opIndex has not yet support for it.

But why not solve it this way: The code

int[] array;
aa[i]++;

compiles into execution of

aa.opIndexAssign(aa.opIndex(i)+1, i);

Now for the support of user defined AA I'd like to suggest a new overload of
opIndex and opIndexAssign or new operator functions opKey, opKeyAssign,
which take a parameter of the key type as first parameter. Also I'd
introduce a base AA type, so that one can easyly derive from it. To use
such a user defined AA class I'd like to suggest the following syntax;

int[char[]]!MyAA an_AA;

The idea is, that any sort of AA is in fact an implcit instanciation of the
builtin AA template, i.e. 

int[char[]] an_AA;

is the same like

int[char[]]!__builtinAA an_AA;

Instead of a struct I'd use classes for this. AAs are dynamic and thus
allocated on the heap anyway. But making them a class would easyly allow to
catch such ambigous things, like Oskar had found.

So logically an AA class would be declared as

class __builtinAA(T, K)
{
};

And a derived class

class MyAA(T, K) : __builtinAA!(T, K)
{
};

or even

class IntToStringAA : __builtinAA(char[], int)
{
};

Eventually derive __builtinAA from a common base, non templated AA type, so
that RTTI clearly recognizes it as AA, and not derive from a templated
class. How about this?

Wolfgang Draxinger




More information about the Digitalmars-d mailing list