Does the unary + operator have any practical use?

前端 未结 9 1757
后悔当初
后悔当初 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:14

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

    template class ref_of{
       T* impl_; // or a more complicated implementation
    public:
       T operator+() const{return *impl_;} 
       operator T&()&{return *impl_;}
    }
    ...
    ref_of r = t;
    auto s = +r; // this forces a copy
    

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

提交回复
热议问题