In this article we will discuss what is std::tuple and how to use it.

what is std::tuple and why do we need it ?

std::tuple is a type that can bind fixed size heterogeneous values together. We need to specify the type of elements as template parameter while creating tuple object.

Creating a std::tuple object

Let’s declare a std::tuple that is a collection of an int, double and std::string i.e.

Now, all the three types of variables are encapsulated in a single object. We can return this tuple object from a function too. So, basically it helps us to return multiple values from a function. Eventually, it helps us to avoid creating unnecessary structs.

Header file required,

Getting elements from a std::tuple

We can get the element hidden in tuple object using std::get function by specifying the index value as template argument.

Let’s get the first element from tuple object i.e.

Similarly get the 2nd and 3rd element from tuple object i.e.

Getting Out Of Range value from tuple

Fetching any element with index more than number of elements encapsulated by tuple will cause compile time error.
For example, trying to get 4th element from tuple will cause compile time error, because this tuple object has only 3 elements i.e.

Wrong type cast while getting value from tuple

Similarly using wrong type while getting element from tuple will also cause error i.e.

Above line will cause compile error because type of first element in tuple is int not string/

Getting value from tuple by dynamic index

Template parameter in std::get whould be compile time constant otherwise it will cause compile time error i.e.

Above line will cause compile error because x is not compile time const. Where as below lines will work fine

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.