C++: Return multiple values of different types from a function

Photo by Markus Spiske on Unsplash

Having done a lot of programming in C++0x and then spending a lot of time on Python programming. I got used to a lot of features in Python and remembered how tedious it is to get the things done in C++. Mind you C++ is definitely faster of the two.

One of the Python features I like the most, is the ability to return multiple values of different types from a function. In Python, when you return multiple values of different types from a function you are actually returning a tuple.

I was happy to find out that since C++11 there is support for a fixed-size collection of heterogeneous values called tuple. The characteristics of a tuple is very similar in Python and C++.

To use a tuple in C++ you have to include the header .

Here is an example of a function that returns a tuple.

A shorter way to make a tuple is by using , where you don't have to specify the data types. However, in this case they need to match the return type.

The compiler tries to convert the values to a data type that matches the return type.

And if the value cannot be implicitly converted they you get a conversion error during compilation.

To access an element in tuple by index you make use of .

Now, if you already have variables defined in which you want to capture the values from a function that returns a tuple. You need to use .

If you want to ignore some elements of the returned tuple, then literally use .

One last thing, to concatenate tuples you can use .

Computer Vision | Machine Learning | Deep Learning https://arccoder.github.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store