Click to See Complete Forum and Search --> : Multiple output arguments


Hamid Mushtaq
February 1st, 2005, 10:27 PM
The C++ alows returning more than one value from a function through pointers and references.
It would have been nice if we could declare multiple output arguments on the left,
for example : -

int, int GetXY()
{
int x, y;
--------------;
return x, y;
}

and call this as

int x, y;
----------;
x, y = GetXY();
or
(x, y) = GetXY();

Note how much this syntax looks natural to the C++ language.

What do you think?

Kheun
February 1st, 2005, 10:41 PM
So far, the STL only provides std::pair. But if you need more than 2, you may want to consider using boost::tuple (http://www.boost.org/libs/tuple/doc/tuple_users_guide.html) which can be downloaded from http://www.boost.org.

wien
February 1st, 2005, 10:47 PM
Unless you are contemplating writing your own compiler, I am fairy certain there is no way you can make that work. (You might be able to hack something similar up by overloading the , operator though.)

Furthermore I don't quite see the point. What you are proposing can easily be acieved by returning a structure with the values you need to return. (std::pair can be used for such a purpose)std::pair<int, int> GetXY()
{
int x, y;
return std::make_pair(x, y);
}EDIT: Too slow. :)

Graham
February 2nd, 2005, 04:14 AM
If two values are sufficiently closely related to warrant being returned at the same time from a function, then those two values deserve to be encapsulated into a single object. From the example, I would assume that x and y are coordinates of a 2d point. You should be passing around Point2D objects in that case, not separate values.