Logical XOR operator






3.10/5 (13 votes)
Sep 6, 2002

188399
A simple implementation of a logical xor operator.
Introduction
Occasionally I come to a need of a logical xor operator (^^) that, obviously, doesn't exist in C++. However, it can be rather easily implemented.
Code listing
#define log_xor || log_xor_helper() || struct log_xor_helper { bool value; }; template<typename LEFT> log_xor_helper &operator ||(const LEFT &left, log_xor_helper &xor) { xor.value = (bool)left; return xor; } template<typename RIGHT> bool operator ||(const log_xor_helper &xor, const RIGHT &right) { return xor.value ^ (bool)right; }
Examples
0 log_xor 0 == false 0 log_xor 5 == true 8 log_xor 0 == true 8 log_xor 5 == false
Other details
- Although they don't have to have the same type, operands should be castable into a simple boolean.
- Precedence of
log_xor
operator is the same as logical or's (||) one. - If you decide to use it, I suggest you to add
log_xor
keyword to the usertype.dat file and insert somewhere the#pragma warning(disable: 4800)
line.