[ Web Proxy ]
URL:
Viewing: https://cpppatterns.com/patterns/return-multiple-values.html [Back]  [Original]

Return multiple values - C++ Patterns
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 36 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

Last Updated

11 December 2017

Source

Fork this pattern on GitHub

Share

Tweet

Feel like contributing? This website is generated from a git repository. If you have something to add or have noticed a mistake, please fork the project on GitHub.

Tweet

logo.svg [logo.svg]

C++ Patterns created by Joseph Mansfield


Web Proxy Viewer  |  New URL  |  Original Page