← Patterns

Return multiple values

1234567891011121314151617#include <tuple> std::tuple<int, bool, float> foo() { return std::make_tuple(128, true, 1.5f); } int main() { std::tuple<int, bool, float> result = foo(); int value = std::get<0>(result); int obj1; bool obj2; float obj3; std::tie(obj1, obj2, obj3) = foo(); }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 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. We make use of the std::make_tuple utility function to create the std::tuple object.

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 16 we use std::tie to assign the return values to each of the given objects. This may not be possible if the objects cannot be constructed beforehand and it removes the possibility of copy elision.

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