Topic: Variable return types


Author: miguelc@cory.Berkeley.EDU (CORAZAO MIGUEL)
Date: Wed, 4 Nov 1992 19:57:38 GMT
Raw View
    I don't really know anything about this news group but I had a question
concerning the new standard for C++ (and perhaps about other languages
as well) and was curious if anyone had an answer.

    I was curious if there is any feature in the new standard for C++ or
for some other language which allows variable return types (i.e. allowing
a function/operator in a class with a given set of arguments to return
different types depending on the where and how it is called). I realize
that this is a very non-standard approach to language design but it
seems that it could be a very useful feature if someone were able to
come up with a way to implement it.  Let give an example as to how
it might be used.

    I wrote a sparse matrix package in C++ which is constructed and
used in the following manner.
 Sparse3 a(DIM1, DIM2, DIM3);

 a[0][0][0] = 5;
 a[1][2][3] += 4;
 a[5][5][5] = a[2][3][4] + a[7][8][1];

    The package is nice in that it is used in almost precisely the same
manner as a conventional array (I'm sure I wasn't the first person to
come up with this idea).  The snag I ran into was that for each number
of dimensions I wanted, I had to have a different class (i.e. a 1-D matrix
is class Sparse1, a 2-D is Sparse2, etc.).  This was necessary since
the operator[] can only return a single type.  So I had to create a
hierarchy of types with each call to operator[] returning the next smaller
type.  It would be nice if there were some way that the language would
automatically take care of these details.
    Perhaps there could be some way of specifying to the compiler that
given a certain declaration of the class, the first n-1 calls to an
operator (given that n was somehow specified) return some sort of reference
to the class which differs for each successive call (but if the operator
is applied to the original class reference, return type is that of a
first call).  The final call to the operator could have some unique
return type.

    Does something like this already exist?

- Miguel Corazao
  miguelc@cory.berkeley.edu