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:
1 2 3 4 5 |
template<typename T> auto ReturnThree(T t) -> tuple<T, T, T> { 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <tuple> using namespace std; template<typename T> auto ReturnThree(T t) -> tuple<T, T, T> { return {t / 9, t / 3, t}; } int main(int argc, char** argv) { tuple<int, int, int> t = ReturnThree(9); // Old and rusty auto [t1, t2, t3] = ReturnThree(9); // New and shiny return 1; } |
One Reply to “Multiple return values”