Applied C++: Return Multiple Values

The best way to return multiple values from a C++17 function

Andriy Berestovskyy
Applied

--

“Do I Know This Already?” Quiz

What is the best way to return multiple values from a C++17 function?

  1. Using output parameters:
    auto output_1(int &i1) { i1 = 11; return 12; }
  2. Using a local structure:
    auto struct_2() { struct _ { int i1, i2; }; return _{21, 22}; }
  3. Using an std::pair:
    auto pair_2() { return std::make_pair(31, 32); }
  4. Using an std::tuple:
    auto tuple_2() { return std::make_tuple(41, 42); }

The answer is at the very bottom of the article.

Use Case: Why to Return Multiple Values?

A typical example is the std::from_chars(), a C++17 function similar to strtol(). But from_chars() returns 3 values: a parsed number, an error code, and a pointer to the first invalid character.

The function uses a mix of techniques: the number is returned as an output parameter, but the error code and the pointer are returned as a structure. Why is so? Let’s analyze…

Analysis

Return Multiple Values Using Output Parameters

--

--

Andriy Berestovskyy
Applied

Engineer at DFINITY.org. In love with software performance and distributed systems. Let’s connect on linkedin.com/in/berestovskyy