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

std::tie

Use case

Unpack tuples into separate variables.

Explanation

std::tie creates a tuple of references, allowing us to unpack a returned tuple into separate variables. We can use std::ignore to skip values we do not need. (Note: C++17 added structured bindings auto [a, b, c] = ... as a cleaner alternative).

Code

#include <cstdint>
#include <iostream>
#include <tuple>

std::tuple<uint64_t, uint64_t, const char *> getSegmentInfo() {
  return std::make_tuple(0x10000000, 0x4000, "__TEXT");
}

int main() {
  uint64_t addr;
  const char *name;

  std::tie(addr, std::ignore, name) = getSegmentInfo();

  std::cout << name << " @ 0x" << std::hex << addr << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/std-tie
__TEXT @ 0x10000000