Applied C++: Return Multiple Values
The best way to return multiple values from a C++17 function
Published in
6 min readDec 19, 2018
“Do I Know This Already?” Quiz
What is the best way to return multiple values from a C++17 function?
- Using output parameters:
auto output_1(int &i1) { i1 = 11; return 12; }
- Using a local structure:
auto struct_2() { struct _ { int i1, i2; }; return _{21, 22}; }
- Using an
std::pair
:auto pair_2() { return std::make_pair(31, 32); }
- 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…