Optimize ternary operator

后端 未结 6 1974
野的像风
野的像风 2021-02-03 18:49

I came across this code written by someone else. Is this usage of the conditional operator recommended or commonly used? I feel it is less maintainable - or is it just me? Is th

6条回答
  •  礼貌的吻别
    2021-02-03 19:42

    This is terrible code.

    While it is often desirable to initialize a variable with a single expression (for example, so we can make it const), this is no excuse to write code like this. You can move the complex logic into a function and call it to initialize the variable.

    void
    example(const int a, const int b)
    {
      const auto mything = make_my_thing(a, b);
    }
    

    In C++11 and later, you can also use a lambda to initialize a variable.

    void
    example(const int a, const int b)
    {
      const auto mything = [a, b](){
          if (a == b)
            return MyThing {"equal"};
          else if (a < b)
            return MyThing {"less"};
          else if (a > b)
            return MyThing {"greater"};
          else
            throw MyException {"How is this even possible?"};
      }();
    }
    

提交回复
热议问题