std::tuple<> in C++

Cengizhan Varlı
3 min readFeb 3, 2023

--

let’s talk on std::pair before tuple.

std::pair is a C++ Standard Library class template that represents a pair of values. It is defined in the <utility> header. A std::pair object holds two values of potentially different types, which can be accessed through its public members first and second.

Here’s an example of how you can use std::pair and std::make_pair<>:

Codes
Output

As shown, pair<> is represents a pair of values.

Especially, When we want to return multiple value from a function, we can use std::pair<>. But std::pair<> can be use for only two values. What if We want more values ? Here comes the need for tuples.

std::tuple is a C++11 Standard Library class template that represents a heterogeneous collection of values. It is defined in the <tuple> header. std::tuple allows you to store multiple values of potentially different types in a single object, similar to std::pair. However, unlike std::pair, std::tuple can store more than two values, and the types of the values stored in a std::tuple can be different from each other. std::tuple was introduced in C++11 and is part of the C++ Standard Library since then.

Codes
Output

As shown above, std::tuple<> usage is similar with std::pair<>. We can assign tuple values as shown above with parameterized ctor.

std::get is a C++ Standard Library function template that allows you to access the elements of a std::tuple object. It is defined in the <tuple> header.

The std::get function takes a std::tuple object and an index, and returns a reference to the element stored at that index in the tuple. The index is specified as a template parameter and must be a constant expression that evaluates to an integer value.

In modern cpp, It is possible to access tuple elements with type as below, Of course unless there are more than one of the same type.

Codes
Output

We can get tuple size as shown below:

Codes
Output

We can write a function that return a std::tuple;

Codes
Output

make_tuple() usage is similar with make_pair().

In follow example, we can want to assign return values of function that return std::tuple, In case of this, we can make an assignment as follows.

Codes
Output

But of course it is ridiculous.

Since Cpp17, We can assign the values ​​returned from the tuple returning function by defining a variable directly as follows.

Codes
Output

--

--

No responses yet