Skip to content

Structured binding

Directly access parts of a type by using named variables

struct SomeStruct
{
    int m_num {4711};
    bool m_valid {false};
};
SomeStruct s = ...;
auto [num, valid] = s;

// Also possible
int myNum;
bool myFlag;
std::tie(myNum, myFlag) = s;

// If you are only interested on some of the data
std::tie(myNum, std::ignore) = s;

Remark:
It is not possible to use std::ignore within an expression like auto [num, std::ignore] = s;”.
In this case you should simply use a regular variable of your own like “auto [num, ignoreFlag]=s;“.

Simplified access to container elements

Instead of using first/second when iterating through a map:

std::map<std::string,int> mapNameAge;
for (const auto & [name, age] = mapNameAge)
{
    std::cut << name << ": " << age << std::endl;
}

Structured binding works for structs, pairs, tuples, arrays.