Something that’s always annoyed me about C++ is that you can only return a single value from a function, and that it’s such a pain in the ass to have to go and create an object just to hold a value that hasn’t been well-defined yet.
In Python, you can say stuff like:
def foo(bar):
return 1, 2, 3, munge(bar), [‘a’, ‘b’]
j, k, l, m, n = foo(‘asdf’)
foo() returns a tuple (an immutable list) containing five items. The first three are integers, the fourth is whatever munge(bar) returns, and the fifth is a list. Being able to do this sort of thing is great. The icing on the cake, however, is being able to unpack them at the other end. In Python, given, say, a 3-element list ‘mylist’, you can say:
a, b, c = mylist
… and now a, b and c will contain the values in mylist. The above example of calling foo unpacks all the return codes into j, k, l, m, and n.
Yesterday, it occurred to me that it’s possible to do a similar thing in C++ by turning a function with multiple returns into an object. The function body becomes the constructor of the object, and all the values it returns become public member variables. For example, the Python function above and its caller might become something like this:
class foo
{
public:
int j, k, l;
string m;
list n;
foo(string bar)
{
j = 1;
k = 2;
l = 3;
m = munge(bar);
n.push_back(‘a’);
n.push_back(‘b’);
}
};
foo ret(“asdf”);
Now, all the returned values can be accessed by looking at ret.j, etc.
A disadvantage here is that this won’t work with methods, only standalone functions. C++ doesn’t seem to let objects access their surrounding scope - the following doesn’t seem to work for me:
class foo
{
public:
int a;
class bar
{
public:
bar()
{
printf(“bar(): a == %d\n”, a);
}
};
};