Well, it can be written for an n-arity tuple in C++0x, but I'm not sure it is worth the time.
The problem with these kinds of things is that it just multiplies code to do something you can do without.
Sure, templates are pretty
, and they satisfy some people's wants for genericity and functional programming, but they really aren't much better than macros.
For every permutation of template arguments you use this trick on, you produce two functions and a structure in your code (the class has one function and one inline ctor), in addition to
the functions whose results you wish to unpack. Rather wasteful, no?
The C++0x code to handle any arbitrary tuple would be an order of magnitude worse, since it would have to be done with a recursive template!
Another young mind ruined by Malik. Consider the following: Two posts before yours I had already posted code that contradicts the assertion in your post, which within the context of this thread cannot be anything other than 'it is not possible to return more than one value.'
Oh, and abusing the language to prove an (incorrect) point doesn't prove anything. The comma operator in your example did exactly what it was supposed to do, and it didn't do what it is not supposed to do. You cannot claim the car failed to operate properly with "it didn't go when I pressed on the brake."
Seriously, even though I haven't read his stuff, any time someone posts with references to Malik's C++ books it is usually something that makes me dislike them even more.
Here is my (humble) advice to you. Pay attention instead of regurgitating. You'll learn more that way.
Personally, I like being able to say, as in Python, things like:
It is very succinct and clear that "myfunc" returns not one, but two --count 'em!-- two
values. Hence, my old little experiment with:
unpair( x, y ) = myfunc( 12 );
That said, it is not in line with the way the language is designed. The best way to do it is as Mr. Malik (ugh) correctly suggested:
Unfortunately, this now becomes ambiguous as to what is happening, unless you've read the documentation to "myfunc" which says something useful like:
void myfunc( int& a, float& b, char c )
or if you are lucky, a comment like:
// Returns a and b given c
At least in C you always knew when something was afoot, since those silly '&'s were not yet banished from calling code:
myfunc( &x, &y, 12 ); /* woah... something must happen to x and y here! */
Even so, this is the more correct solution because it reduces bloat and complexity. Related code is still properly modularized in one function, type errors are not compromised, and the code is still succinct and quick. That is, this is really the most efficient
way to do it.
Hmm, I just thought of another experiment which may be both efficient and simple, with the ability to extract any n-tuple expressed as a struct
or maybe a pair
I'll post back a little later.