Returning Multiple Values from a Function
How can I use tuples to return multiple values from a C++ function?
Tuples provide a clean way to return multiple values from a function without resorting to output parameters or complex data structures. Here's an example:
#include <string>
#include <tuple>
std::tuple<int, std::string> GetInfo(int id) {
// Fetch player data...
int score = 100;
std::string name = "John";
return {score, name};
}
int main() {
auto [playerScore, playerName] = GetInfo(42);
// Use playerScore and playerName...
}
The GetInfo()
function returns a tuple containing the player's score and name. We can use structured bindings to conveniently unpack the returned values into separate variables.
This approach is more expressive than output parameters and avoids the overhead of creating a dedicated struct or class just for returning related values. Tuples shine for small numbers of values - for larger groups of data, a class is usually more appropriate.
Tuples and std::tuple
A guide to tuples and the std::tuple
container, allowing us to store objects of different types.