C++17 introduced structured binding, a syntax that initializes multiple entities by elements or members of an object. It is handy to emulate
several return values from a function.
Suppose you have a function that returns a pair:
std::pair<std::string, std::string> getPair();
Structured binding allows you to bind the members of the std::pair
class directly to new names:
auto [firstName, lastName] = getPair();
The names firstName
and lastName
are called structured bindings. As you can see, structured binding makes the code more
readable as it allows binding values to names that carry information about their purpose.
Structured binding works with:
- Raw arrays, by binding a name to each element
- Any type that has a tuple-like API
- Classes and structures where all non-static data members are publicly accessible
This rule will detect places where std::pair
and std::tuple
can be effortlessly replaced by a structured binding.
Noncompliant code example
void printingMap(const std::map<int, std::string>& map) {
for (const auto& elem : map) { // Noncompliant
std::cout << elem.first << ": " << elem.second << "\n";
}
}
Compliant solution
void printingMap(const std::map<int, std::string>& map) {
for (const auto& [key, value] : map) { // Compliant
std::cout << key << ": " << value << "\n";
}
}