C++ Structured Binding

2018-09-12 ☼ codingc++

forgive the double-escaped ampersands! This is a bug in blot.im 😔

C++17 adds really nice syntax that lets you quickly bind into things like std::pair and std::tuple and even your own structs and classes. This is called Structured Binding.

Simple example:

struct Record {
    std::string name;
    long age;
std::vector<Record> records {
    {"Ryan", 173},
    {"Charles", -7},

for(auto&amp;&amp; [name, age] : records) {
    std::cout << name << "," << age << std::endl;

This also works on STL associative structures when iterating:

std::unordered_map<std::string, int> records = {
    {"Ryan", 137},
    {"Winnie", 7}
for(auto&amp;&amp; [k, v] : records) {
    std::cout << "k=" << k << ", v=" << v << std::endl;

What’s great about this is that there is no performance penalty for using it, it’s just syntax-sugar.

It’s best” to use auto&amp;&amp; to get reference-collapsing. This means that you don’t change the lvalue- or rvalue-ness of the values to which you’re binding and you avoid creating copies. Use plain auto if you do want copies. There is currently no way to specify auto&amp;&amp; for some items and plain auto (copy) for others. Similarly you can specify const and all items will be const.