C++ Best Tricks to Save your Life -Modern and Friendly C++ Syntax: Unpack Tuple

Matt Wang
2 min readNov 16, 2022

A series of articles that compare other languages with C++ and introduce new and cool features of the modern C++.

Modern and friendly C++ syntax: Unpack tuple

We can do list, tuple binding (or unpacking list) in Ruby, Python, Golang, Rust and lots of other languages.
Let’s see some examples.

Ruby

a, b, c = 1, 2, 'hello'  # a=1, b=2, c='hello'
a, b, c = [1, 2, 'hello'] # a=1, b=2, c='hello'
a, b, c = [1, 2, 'hello', 4, 5] # a=1, b=2, c='hello'
a, b, *c = [1, 2, 'hello', 4, 5] # a=1, b=2, c=['hello',4,5]

Python

a, b, c = 1, 2, 'hello'  # a=1, b=2, c='hello'
a, b, c = [1, 2, 'hello'] # a=1, b=2, c='hello'
a, b, c = [1, 2, 'hello', 4, 5] # Does not work in Python
a, b, *c = [1, 2, 'hello', 4, 5] # a=1, b=2, c=['hello',4,5]

Golang

a, b, c := 1, 2, "hello" // a=1, b=2, c='hello'
// The other 3 cased do not work in Golang

Rust

let (a, b, c) = (1, 2, "Hello"); // a=1, b=2, c='hello'
let [a, b, c] = [1, 2, 3]; // a=1, b=2, c=3
// The other 2 cased do not work in Golang

Discussion
It does not really make big difference if we only use the unpack syntax to initialise variables. But if we perform this magic on return values, it becomes highly useful.
For example, a function returns values that are from different models.

def user_stats(user_id)
user = find_by_id(user_id)
membership = user.membership
default_address = user.default_address
return [user.friendly_name, membership.level, default_address.to_s]
end

name, level, address = user_stats(12345)

However, the code above in classical C++ looks inelegant:

void get_user_stats(int user_id, std::string& name, std::string& level, std::string& default_address){
User user = find_by_id(user_id);
name = user.get_friendly_name();
level = user.membership.get_level();
default_address = user.get_default_address();
}

std::string& name, level, default_address;
get_user_stats(name, level, default_address);

Better solution for C++

We know the problem, let’s see the better solution (since c++17):

std::tuple<std::string, std::string, std::string> get_user_stats(int user_id) {
User user = find_by_id(user_id);
std::string name = user.get_friendly_name();
std::string level = user.membership.get_level();
std::string default_address = user.get_default_address();
return {name, level, address};
}

auto [name, level, address] = get_user_stats(123);

We use tuple binding in the code above, and you can find more information here.

Conclusion

Programming languages are evolving faster than ever, and eventually will go to the same end: better performance with friendly syntax. Study in modern syntax will reduce the boilerplate code and make the code more intuitive, which improves the maintainability and allows the software engineer to focus the business logic.

--

--

Matt Wang

Empowering others through handy and innovative tech solutions and sharing knowledge. Stay tuned with my new articles.