Std::tie

Written by on December 25, 2022 in C++, Programming with 0 Comments

std::tuple is a widely used abstraction in C++ and has been around since C++11. It is a generalization of std::pair.

std::tie is convenient when we want to create a tuple of lvalue references to existing variables. It is a function template commonly used to unpack a tuple into individual objects.

std::tie Example

std::tie Example

In the above example, we first define a tuple object comprising an integer, a string and a double. We then use std::tie to assign the respective values of the tuple to the individual variables “I” and “d”. This works because, as mentioned earlier, std::tie returns a tuple with lvalue references to its parameters. Notice the use of std::ignore to skip an element of the RHS tuple.

The main difference between structured binding and std::tie is that the former both creates and initializes at the same time, whereas the latter only assigns values to already existing variables. The following example shows this.

Compared with Structured Binding

Compared with Structured Binding

The last point to keep in mind about std::tie is that it requires modifiable lvalue parameters when it is used to “unpack” a tuple. Take a look this code:

Parameter Requirements

Parameter Requirements

The reason why line 35 won’t compile is because std::tie is used on the LHS of assignment to unpack a tuple, but its parameters are literals. In line 39, even though the parameter to std::tie is an lvalue, it is a const object and hence cannot be modified by the unpacking assignment.

Line 43 is OK because here std::tie is used on the RHS and there is no modification to its argument. Line 48 shows that we can use the std::get function to access an individual element of the tuple returned by std::tie and update it with a new value.

You can download the sample code here.

Merry Christmas and Happy New Year 2023!

Tags: , , ,

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

Top