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

后端 未结 1 1637
太阳男子
太阳男子 2021-01-20 10:21

I\'d like to use C++ 17 structured bindings to assign a value to a class member variable, like this:

#include 
#include 

struct         


        
相关标签:
1条回答
  • 2021-01-20 11:18

    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.

    0 讨论(0)
提交回复
热议问题