Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!usc!snorkelwacker!ai-lab!lem!tmb From: tmb@lem.ai.mit.edu (Thomas M. Breuel) Newsgroups: comp.lang.c++ Subject: Re: Extensions to [] Message-ID: <8903@life.ai.mit.edu> Date: 7 Jun 90 22:52:11 GMT References: <1589@ole.UUCP> Sender: news@wheaties.ai.mit.edu Reply-To: tmb@ai.mit.edu Organization: MIT Artificial Intelligence Lab Lines: 58 In article <1589@ole.UUCP>, powell@ole.UUCP (Gary Powell) writes: |>I am new to C++ but after a seminar and some play time I tried writting |>a class for two diminsional arrays. What I found myself wanting was |>a overloaded operator [][](int)(int). However my GNU g++ 1.35 compiler |>complains bitterly when I tried to code this. Why not use the (int,int) |>operator? Well I was using that for the initialization. It would seem to |>me that since C allows array[][] access that C++ should allow overloading |>of this also. |> |>With this background has there been any discussion on the overloading of |>[][] ....[]? |> |>And is this a reasonable extension to the language? |> |>Resons for doing this are that N'dim. arrays are a pain to pass |>to functions. With a class I can add the extra information for bounds |>checking and pass the arguement as a single pointer and let the compiler |>call my code to access the array. Overloading "operator[][]" is not really the right thing to do-- there is no such thing as an "operator[][]". Probably the best solution is to break with tradition and make "operator[]" completely analogous to "operator()" in the treatment of "multiple arguments" and commas. This would constitute a minor incompatiblity with ANSI C, since ANSI a[1,2] would now have to be written a[(1,2)], but this should not affect a lot of code, and it should be easy to fix where it occurs. An ANSI C compatible solution to the problem would be to treat "operator[]" analogous to "operator()" iff it is used with a non-pointer type. If someone implemented this in GNU C++, I'm sure it would catch on... it is simply a very useful feature. Thomas PS: The popular approach to "overloading operator[][]" is to have the first operator[] return a "partially dereferenced result", and have the second operator[] complete the job: struct floatArray2d = { ... partiallyDereferencedFloatArray2D operator[](int) { ... } }; struct partiallyDereferencedArray2D = { floatArray2D array; int index1; float operator[](int) { ... } }; This is, of course, undesirably complex and messy. Incidentally, the same kludge is used for defining the equivalent of CommonLisp SETF methods, and, again, a simple mechanism would be desirable.