Basic use of Tuples C++11

Basic use of Tuples in C++11

Tuples are an amazing feature in C++. Tuples are specified in C++11 standard (ISO/IEC 14882:2011), i.e. they are a new introduction in c++11. So if you are more used to traditional c++, tuples will come as a surprise for you. It happened to me as well and I am not that old (quite yet)! They are a great addition to generic programming and brings C++ to a whole new level of usability. Of course we have had ways to do exactly the same things that tuples does but now that it is a part of the standard language, it makes sense to use this feature instead of cooking something of our own. I see tuples as an important feature like dictionary in python (more or less). Tuples are amazing and you can feel the power when you start using them. Auto types and tuples make a great combination for very nice cool features previously rarely thought of (multiple return values from a function anyone). Anyways, I don’t see people really appreciating the flexibility being provided by our beloved language. Stefan Lavavej (@StefanTLavavej) maintaining the STL implementation, working at @microsoft, has a very nice talk in CPPCon 2016 that I recommend you watch. Check it out below. This is the one that got me interested in tuples.

So, now that you are back after watching the video, lets start using Tuples! Below is the code on ideone.com for you to play with. It is very simple. All it does is ask for an input number, calls a function which returns a tuples with 4 string elements. The output is formatted from the data returned from the function call. Tuples is templated so one can use anything inside, even custom classes.

std::make_tuple() is used to create the tuple and std::get(tuple_var) to get the individual values out of it. You can also use std::tie() to define varaible names and can access them instead of accessing by index. @StefanTLavavej video shows more details and go through it if you haven’t done that already. Happy coding using tuples.

Send in your comments & Suggestions. Follow me on Twitter @wolverine2k and share the love by clicking the buttons below and posting this on your social networks.