A min= idiom in C++?

后端 未结 7 809
旧巷少年郎
旧巷少年郎 2021-02-09 22:10

We use

x += y

instead of

x = x + y

And similarly for *,/,- and other operators. Well, what about

7条回答
  •  臣服心动
    2021-02-09 22:50

    It's certainly not idiomatic, but you might be able to use something called named operators (see these Q&As here and here, developed by @Yakk and @KonradRudolph), and write

    x = y;
    

    which is made possible by overloading operator< and operator>, combined with a clever wrapped named_operator. The full code is given by the link above, but uses code like

    template 
    inline auto operator >(named_operator_lhs const& lhs, T2 const& rhs)
        -> decltype(lhs.f(std::declval(), std::declval()))
    {
        return lhs.f(lhs.value, rhs);
    }
    

    Using std::min as template argument for the template parameter F, would update the lhs of the expression with the min of the lhs and rhs.

提交回复
热议问题