Modern C++ idoms and recipes

meshell
2,322 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <map>
#include <string>
#include <iostream>
using namespace std::string_literals;
struct address_t {
std::string street;
unsigned plz;
std::string city;
};
int main() {
std::map<std::string, address_t> address_book;
const auto hans = "Hans Meister"s;
const auto hans_address = address_t{"Maihofstrasse 49"s, 6000u, "Luzern"s};
auto it = address_book.begin();
auto inserted = false;
std::tie(it, inserted) = address_book.insert({hans, hans_address});
std::cout << "inserted = " << inserted << std::endl;
std::cout << "name = " << it->first << std::endl;
std::cout << "address = " << it->second.street << ", "
<< it->second.plz << ", "
<< it->second.city << std::endl;
it = address_book.find(hans);
if (it != address_book.end()) {
std::cout << hans << " is in address book living in " << it->second.city << std::endl;
} else {
std::cout << hans << " is not in address book\n";
}
const auto peter = "Peter Müller"s;
it = address_book.find(peter);
if (it != address_book.end()) {
std::cout << peter << " is in address book living in " << it->second.city << std::endl;
} else {
std::cout << peter << " is not in address book\n";
}
const auto peter_address = address_t{"Langstrasse 49"s, 8000u, "Zürich"s};
auto result = address_book.insert({peter, peter_address});
if (result.second) {
std::cout << "Inserted " << result.first->first << std::endl;;
} else {
std::cout << "Did not insert " << result.first->first << std::endl;;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content