Tutorial by Examples

Parameters can be used for returning one or more values; those parameters are required to be non-const pointers or references. References: void calculate(int a, int b, int& c, int& d, int& e, int& f) { c = a + b; d = a - b; e = a * b; f = a / b; } Pointers: ...
C++11 The type std::tuple can bundle any number of values, potentially including values of different types, into a single return object: std::tuple<int, int, int, int> foo(int a, int b) { // or auto (C++14) return std::make_tuple(a + b, a - b, a * b, a / b); } In C++17, a braced init...
C++11 The container std::array can bundle together a fixed number of return values. This number has to be known at compile-time and all return values have to be of the same type: std::array<int, 4> bar(int a, int b) { return { a + b, a - b, a * b, a / b }; } This replaces c style ar...
The struct template std::pair can bundle together exactly two return values, of any two types: #include <utility> std::pair<int, int> foo(int a, int b) { return std::make_pair(a+b, a-b); } With C++11 or later, an initializer list can be used instead of std::make_pair: C++11 ...
A struct can be used to bundle multiple return values: C++11 struct foo_return_type { int add; int sub; int mul; int div; }; foo_return_type foo(int a, int b) { return {a + b, a - b, a * b, a / b}; } auto calc = foo(5, 12); C++11 Instead of assignment to indi...
C++17 C++17 introduces structured bindings, which makes it even easier to deal with multiple return types, as you do not need to rely upon std::tie() or do any manual tuple unpacking: std::map<std::string, int> m; // insert an element into the map and check if insertion succeeded auto [i...
We can provide a consumer that will be called with the multiple relevant values: C++11 template <class F> void foo(int a, int b, F consumer) { consumer(a + b, a - b, a * b, a / b); } // use is simple... ignoring some results is possible as well foo(5, 12, [](int sum, int , int , i...
A std::vector can be useful for returning a dynamic number of variables of the same type. The following example uses int as data type, but a std::vector can hold any type that is trivially copyable: #include <vector> #include <iostream> // the following function returns all integers...
Several values of the same type can be returned by passing an output iterator to the function. This is particularly common for generic functions (like the algorithms of the standard library). Example: template<typename Incrementable, typename OutputIterator> void generate_sequence(Increment...

Page 1 of 1