TIL an obscure C++ thing, trying to learn more
char x = 65;
std::cout << x << " = " << +x << '\n';
RESULT: "A = 65"
How does unary + operator, (returns *this by-value or const reference), cause the stream to output as integer?
#cpp #programming #gamedev #cplusplus
-
-
Replying to @timbeaudet
Shafik Yaghmour Retweeted Shafik Yaghmour
Shafik Yaghmour added,
Shafik Yaghmour @shafikyaghmourUnary plus feels like a sneaky C-style cast b/c all it does is invoke integer promotions and conversions but we get no warnings for this. +'a' // Promote to int foo( +[](){} );// conv to func ptr Live https://wandbox.org/permlink/a7Won2zyUwx7hPNa … https://stackoverflow.com/a/30791078/1708801 …#cplusplus#programming pic.twitter.com/477G2j0eEd1 reply 0 retweets 0 likes -
Replying to @shafikyaghmour
That doesn't help, I guess I should be more clear, how does returning the type by value or const ref, wind up promoting it to an integer. IE, in theory one could write; type operator+() const { return *this; } And supposedly get an integer promotion, or, (next tweet)
1 reply 0 retweets 0 likes -
Replying to @timbeaudet @shafikyaghmour
Did I just misunderstand and the prototype is: int operator+() const { return *this; }
2 replies 0 retweets 0 likes -
Replying to @timbeaudet @shafikyaghmour
5.3.1 ¶6: "The operand of the unary + operator shall have arithmetic, enumeration, or pointer type and the result is the value of the argument. Integral promotion is performed on integral or enumeration operands. The type of the result is the type of the promoted operand."
1 reply 0 retweets 0 likes
Most of the time when people talk about operator behaviour like intification with op+, they're talking about how they behave for builtin types. Overloads for user-defined types can do pretty much anything the user desires, as long as the bare requirements are met.
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.