| [ Web Proxy ] |
| Viewing: https://cpppatterns.com/patterns/return-multiple-values.html | [Back] [Original] |
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.
Return multiple values of different types from a function.
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.
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.
| Web Proxy Viewer | New URL | Original Page |