I\'d like to use C++ 17 structured bindings to assign a value to a class member variable, like this:
#include
#include
struct
Use std::tie to assign values to existing objects:
std::tie(result_, error_) = square_root(input);
That's why it was added to C++11. Of course, you'd need to forego using Result
in favor of a std::tuple
. Which IMO is better for such ad-hoc "return multiple things" scenarios.
Structured bindings are exclusively for declaring new names.
Another approach, which could be even better, since C++1z is on the table, is to not re-invent the wheel. Return a std::optional
auto square_root(double input) {
return input < 0 ? std::nullopt : std::optional{std::sqrt(input)};
}
This has the clear semantics of "there may be a value, or not".
By the way, unconditionally calling std::sqrt
with a negative input is a bad idea. Especially if you don't configure your floating point environment in any special way prior.