Is it possible to use structured bindings to assign class members?

笑着哭i 提交于 2019-12-02 02:50:48

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!