Multiple return values (was Re: Const Considerations)
James Kanze wrote:
Mulitple return values would change a lot if we also had
multiple assigns, like some languages. But we don't, and I
can't quite see how to make them fit into the C++ grammar.
It occurred to me recently that auto variables and the proposed
extension to initializer lists (both expected to be in the next
standard) could provide most of what is necessary for multiple return
values. Consider (not currently legal):
template<class FwdIt, class Ty>
struct {
FwdIt lower_bound;
FwdIt upper_bound;
} equal_range(
FwdIt first,
FwdIt last,
const Ty& val)
{
FwdIt lower;
FwdIt upper;
... calculate lower and upper ...
return { lower, upper };
}
int main()
{
std::vector<int> v;
... fill v with ordered values ...
auto equal = equal_range(v.begin(), v.end(), 5)
std::cout << "lower = " << equal.lower_bound
<< ", upper = " << equal.upper_bound << std::endl;
}
The return statement will be legal in the next standard. So will the
assignment in main. All that is necessary is to allow defining an
anonymous type as the return type for a value. The type will need to
have a hidden unique name, and be the same type for multiple declaration
of the same function.
To make it neater, one could define
auto f(type1 a, type2 b) -> (type3 c, type4 d);
to mean
struct {type3 c; type4 d;} f(type1 a, type2 b);
extending the new function declaration syntax introduced in the decltype
proposal.
For extra interoperability one might want to add a templated conversion
operator as follows:
struct {
type3 c;
type4 d;
template<class T>
operator T() { return T(c, d); }
};
allowing the function to be used directly to initialise any object with
an appropriate constructor.
Yechezkel Mett
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]