Modern C++ idoms and recipes

meshell
59.2K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Structured Bindings

Structured bindings is a new C++ language feature shipping with C++17. It gives us the ability to declare multiple variables initialized from a tuple, pair or struct.

Example

With C++11/14 you could use std::tie to bind the elements of a pair or tuple to variables:

const auto tuple = std::make_tuple(1, 'a', 2.3);
//...

// first declare the variables
int i;
char c;
double d;

// now we can unpack the tuple
std::tie(i, c, d) = tuple;

With C++17 this becomes much easier:

const auto tuple = std::make_tuple(1, 'a', 2.3);
// ...
const auto [ i, c, d ] = tuple;

DIY

Refactor the code to use structured bindings when ever possible
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content