Re: Rvalues and returning multiple values wrapped in a tuple
On 22 Jan., 03:53, Patrik Kahari wrote:
// Say I wanted this in some pseudo c++:
// (bool, int) do_something(int a, int b, int c) {
// return (true, a-b+c);
// }
// (bool valid, int value) = do_something(123, 456, 789);
//I would have to do something like this instead:
#include <tuple>
std::tuple<bool, int> do_something(int a, int b, int c) {
return std::tuple<bool, int>(true, a-b+c);
}
...
std::tuple<bool, int> go_between = do_something(123, 456, 789);
bool valid = std::move(std::get<0>(go_between));
int value = std::move(std::get<1>(go_between));
That's a lot of syntactic noise and introduced the possible bug that
someone might use the go_between lvalue after its been moved from. Is
there a better way?
First of all, std::move is useless here since moving and copying is
equivalent for PODs and bool and int are POD types.
Secondly, here are alternatives:
1. create tuple<bool&,int&> and assign to it:
bool valid; int value;
std::tie(valid,value) = do_something(123,456,789);
2. Keep the tuple and create aliases for its members:
auto t_ = do_something(123,456,789);
auto& valid = std::get<0>(t_);
auto& value = std::get<1>(t_);
3. use Boost.Optional
http://www.boost.org/doc/libs/1_42_0/libs/optional/doc/html/index.html
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]