Does the unary + operator have any practical use?

前端 未结 9 1749
后悔当初
后悔当初 2020-12-03 16:58

Was the unary + operator only included for symmetry with the unary - operator, or does it find some practical use in C++ code?

Searching h

相关标签:
9条回答
  • 2020-12-03 17:34

    Since for arithmetic variables operator+ generates a new value. I use it to generate value copies of reference-like (proxy) types.

    template<class T> class ref_of{
       T* impl_; // or a more complicated implementation
    public:
       T operator+() const{return *impl_;}
       operator T&()&{return *impl_;}
    }
    

    Another option is to use operator* but then the ref_of can be confused with a pointer-like object.

    0 讨论(0)
  • 2020-12-03 17:36

    If you explicitly stay clear of any number value semantics for a class, any operator overloading is clear not to "do as the ints do". In that case, the unary plus may get any meaning, doing much more than just returning *this

    Prominent example: Boost.Spirit's unary plus for the embedded EBNF's Kleene Plus generates a parser rule that lets it's argument (a parser rule as well) match one or more times.

    0 讨论(0)
  • 2020-12-03 17:37
    char ch = 'a';
    std::cout << ch << '\n';
    std::cout << +ch << '\n';
    

    The first insertion writes the character a to cout. The second insertion writes the numeric value of ch to cout. But that's a bit obscure; it relies on the compiler applying integral promotions for the + operator.

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