C++17 gives us an elegant way to return multiple values from a function using structured binding.
Here’s how we can declare a function that returns 3 values:
templateauto ReturnThree(T t) -> tuple { return {t / 9, t / 3, t}; }
This function takes one argument of type
T, and returns a
tuple<T, T, T>of 3 values.
In order to get the return values in C++11 we would have to write the following:
tuple<int, int, int> t = ReturnThree(9);
But with C++17 and structured binding syntax we can write:
auto [t1, t2, t3] = ReturnThree(9);
Much cleaner code this way 🙂
Complete listing:
#includeusing namespace std; template auto ReturnThree(T t) -> tuple { return {t / 9, t / 3, t}; } int main(int argc, char** argv) { tuple t = ReturnThree(9); // Old and rusty auto [t1, t2, t3] = ReturnThree(9); // New and shiny return 1; }
One Reply to “Multiple return values”