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.

#include <cstdlib>
#include <iostream>
#include <tuple>

using namespace std;

auto get_tuple(string name) {
    return make_tuple(name, 1);
}

int main(int argc, char** argv) {
    auto t3 = get_tuple("FOO");
    auto t4 = get_tuple("BAR");
    
    cout << get<0>(t3) << endl << get<0>(t4) << endl;
    
    return 0;
}

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:

    auto t1 = std::make_tuple("foo", 1, 2);
    auto t2 = std::make_tuple("bar", 1.0, 2);

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 *