A min= idiom in C++?

后端 未结 7 816
旧巷少年郎
旧巷少年郎 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:40

    NO. There is no such thing, you'll have to do with std::min(x,y);

    0 讨论(0)
  • 2021-02-09 22:44

    You can't extend the language in this way. The closest you can come is something like:

    template <typename T, typename U>
    T&
    mineq( T& lhs, U rhs )
    {
        if ( rhs < lhs ) {
            lhs = rhs;
        }
        return lhs;
    }
    

    This would allow writing:

    mineq( x, y );
    

    I question whether it's worth the bother, however.

    0 讨论(0)
  • 2021-02-09 22:45

    C++ has a limited set of operators and keywords.

    What you are trying to do is outside the C++ specification and is not possible.

    You can do the comparison and assignment with this one-liner if you want:

    x = (x < y) ? x : y;

    0 讨论(0)
  • 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 <min>= 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 <typename T1, typename T2, typename F>
    inline auto operator >(named_operator_lhs<T1, F> const& lhs, T2 const& rhs)
        -> decltype(lhs.f(std::declval<T1>(), std::declval<T2>()))
    {
        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.

    0 讨论(0)
  • 2021-02-09 22:50

    You cannot write this kind of sentences, they are reserved for the built-in syntaxt

    0 讨论(0)
  • 2021-02-09 23:00

    No, it is not possible to create new custom operators.

    You have a few available solutions though:

    llama_min_age = std::min(x, y);
    llama_min_age = (x < y ? x : y);
    

    Or even a macro if you want to:

    #define MIN(x, y) ((x) < (y) ? (x) : (y))
    

    About the macro: it can lead to vicious bug, so I would prefer to use one of the first two solutions.

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