Back to these C++ tuples

Okay, now that Christmas and New Year is finally over and I’ve got pockets like a white eared elephant, I decided to have another blast at these tuple things because they were doing my head in.

All along I’ve been thinking that a class/struct would be much better. In most cases I would be right, but then I thought, “Hang on, this is C++. Let me check if I can return a tuple from a function.”

Hey, turns out I could.

And voila, just like that I can now return multiple values from a function.

The one thing you have to be careful of is the setup. A typo mistake or a type mistake can and will cost hours of debugging so be wary of things like this:

Now even if I added to the first tuple “foo”, 1f, 2, this would not match the second as the second tuple uses a double value. A pain for debugging.

Just the fact you can return multiple values of data without having to define a complete struct or class is actually quite a nice addition.

I have done some research into tuples now and found that these use cases are good, but for larger data, it is so much better even to still use a struct/class because with the above examples you still are having to use index values to access the data items. Where as a struct/class, the data items are named.

Although this however can be overcome by using enums, larger tuples are very likely better off being converted to a struct/class.

Even after 35+ years of programming I’m still learning.

Time to move onto something else… Bigger…

Leave a Reply

Your email address will not be published. Required fields are marked *