C++ Structured Binding

2018-09-12 ☼ codingc++

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&& [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&& [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&& 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&& for some items and plain auto (copy) for others. Similarly you can specify const and all items will be const.