← Patterns

Return multiple values

1234567891011121314#include <tuple> std::tuple<int, bool, float> foo() { return {128, true, 1.5f}; } int main() { std::tuple<int, bool, float> result = foo(); int value = std::get<0>(result); auto [value1, value2, value3] = foo(); }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++17 or newer. Other versions:

Intent

Return multiple values of different types from a function.

Description

The foo function on lines 3–6 returns a std::tuple representing multiple values of different types.

On line 10, we call this function and store the result. We then get the first of the returned values with std::get on line 11.

Alternatively, on line 13 we use a structured binding declaration to declare and initialize variables with the returned values. The types of these variables are deduced automatically.

If the values are closely and logically related, consider composing them into a struct or class type.

Contributors

  • Joseph Mansfield

Last Updated

11 December 2017

Source

Fork this pattern on GitHub

Share