Power of C++ Structured Bindings

 Introduction:

Structural Binding helps us to write simple code by unpacking the elements from tuple-like objects.

To understand Structural Binding, we need to understand a data structure that holds(or packs) different data. A few such data structures are std::tuple, std::pair, arrays or we can write our own data structure to hold the data.

One practical application of C++ tuples is in returning multiple values from a function. Before C++11, when tuples were introduced, programmers often resorted to passing pointers or references to variables into functions to return multiple values. However, this approach could be error-prone and less expressive. Tuples provide a cleaner and more idiomatic way to handle this scenario.

Next comes Structural Binding, which helps us write simple and clean code. To illustrate, here is a simple example:

The below example will return the sum and product for two numbers: Without structural binding, we use  std::tuple<int, int> result to unpack the tuples.

#include <iostream> 
#include <tuple> 
// Function to calculate the sum and product of two numbers 
std::tuple<int, int> calculate(int a, int b) 

    int sum = a + b; 
    int product = a * b; 
    return std::make_tuple(sum, product); 

int main() 

    int x = 5, y = 3;
    std::tuple<int, int> result = calculate(x, y);
     int sum, product; 
    std::tie(sum, product) = result; 
    std::cout << "Sum: " << sum << std::endl; 
    std::cout << "Product: " << product << std::endl; 
    return 0; 
}


The below code uses Strutual binding:

#include <iostream>
#include <tuple>

// Function to calculate the sum and product of two numbers
std::tuple<int, int> calculate(int a, int b) {
    int sum = a + b;
    int product = a * b;
    return std::make_tuple(sum, product);
}

int main() {
    int x = 5, y = 3;
    auto [sum, product] = calculate(x, y);

    std::cout << "Sum: " << sum << std::endl;
    std::cout << "Product: " << product << std::endl;

    return 0;
}