Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Structured bindings

Use case

Unpack tuples, pairs, arrays and structs cleanly.

Explanation

auto [a, b, c] = expr unpack tuple-like objects and aggregate types (e.g. plain structs with public members) into named variables. Cleaner than std::tie and std::get.

Code

#include <cstdint>
#include <iostream>
#include <map>

struct Symbol {
  bool found;
  uint64_t addr;
  const char *name;
};

Symbol findSymbol([[maybe_unused]] const char *name) {
  return {true, 0x10001000, "_main"};
}

int main() {
  auto [found, addr, name] = findSymbol("_main");
  std::cout << name << " @ 0x" << std::hex << addr << "\n";

  std::map<uint64_t, const char *> symbols{{0x10001000, "_main"},
                                           {0x10002000, "_helper"}};

  for (const auto &[addr, name] : symbols) {
    std::cout << name << " @ 0x" << std::hex << addr << "\n";
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/structured-bindings
_main @ 0x10001000
_main @ 0x10001000
_helper @ 0x10002000