Does the unary + operator have any practical use?
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.
Symmetry with unary -
isn't entirely useless; it can be used for emphasis:
const int foo = -1;
const int bar = +1;
And an overloaded unary +
can be used to denote an operation that yields the same logical value as its operand, while performing some non-trivial computation. (I've seen this done for type conversions in Ada, which permits unary +
, but not conversions, to be overloaded.) I don't have a good C++ example to hand, and one could argue that it would be poor style. (Then again, I've seen plenty of rants about overloading <<
.)
As for why C++ has it, it's probably largely for consistency with C, which added it with the 1989 ANSI standard. The C Rationale just says:
Unary plus was adopted by the C89 Committee from several implementations, for symmetry with unary minus.