Home Item 19 - Structured bindings (English)
Post
Cancel

Item 19 - Structured bindings (English)

Scenario

When writing Python, we can conveniently unpack values directly into variables without needing to first store the function’s return value in an intermediate variable and then extract x and y separately.

1
2
3
4
5
6
# Multiple return values unpacking
def get_coordinates():
    return (10, 20)

x, y = get_coordinates()
print(f"x: {x}, y: {y}")

C++17 has introduced this capability as well.

C++17 introduced structured bindings, a new syntax that allows us to decompose and bind members of tuple-like structures, structs, or arrays into individual variables. This makes the code more concise and readable.

Syntax The basic syntax for structured bindings is as follows:

1
auto [var1, var2, ..., varN] = expression;

Tuple Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <tuple>

std::tuple<int, int, std::string> getPerson() {
    return { 35, 35, "KD" };
}

int main() {
    auto [age, number, name] = getPerson();

    std::cout << "Age: " << age << '\n';
    std::cout << "Number: " << number << '\n';
    std::cout << "Name: " << name << '\n';

    return 0;
}

Struct Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

struct Person {
    int age;
    int number;
    std::string name;
};

int main() {
    Person person = {39, 23, "LBJ"};

    auto [age, number, name] = person;

    std::cout << "Age: " << age << '\n';
    std::cout << "Number: " << number << '\n';
    std::cout << "Name: " << name << '\n';

    return 0;
}

Array Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main() {
    int arr[3] = {1, 2, 3};

    auto [a, b, c] = arr;

    std::cout << "a: " << a << '\n';
    std::cout << "b: " << b << '\n';
    std::cout << "c: " << c << '\n';

    return 0;
}

Benefits

  1. Improved Code Readability: Structured bindings make the code more concise and easier to read, especially when dealing with composite types.

  2. Simplified Variable Declaration: When extracting values from a function that returns multiple values, structured bindings can avoid multiple variable declarations, simplifying the code.

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍