Logical XOR operator in C++?

后端 未结 11 1240
轮回少年
轮回少年 2020-11-29 15:54

Is there such a thing? It is the first time I encountered a practical need for it, but I don\'t see one listed in Stroustrup. I intend to write:

// Detect wh         


        
11条回答
  •  攒了一身酷
    2020-11-29 16:18

    There was some good code posted that solved the problem better than !a != !b

    Note that I had to add the BOOL_DETAIL_OPEN/CLOSE so it would work on MSVC 2010

    /* From: http://groups.google.com/group/comp.std.c++/msg/2ff60fa87e8b6aeb
    
       Proposed code    left-to-right?  sequence point?  bool args?  bool result?  ICE result?  Singular 'b'?
       --------------   --------------  ---------------  ---------- ------------  -----------  -------------
       a ^ b                  no              no             no          no           yes          yes
       a != b                 no              no             no          no           yes          yes
       (!a)!=(!b)             no              no             no          no           yes          yes
       my_xor_func(a,b)       no              no             yes         yes          no           yes
       a ? !b : b             yes             yes            no          no           yes          no
       a ? !b : !!b           yes             yes            no          no           yes          no
       [* see below]          yes             yes            yes         yes          yes          no
       (( a bool_xor b ))     yes             yes            yes         yes          yes          yes
    
       [* = a ? !static_cast(b) : static_cast(b)]
    
       But what is this funny "(( a bool_xor b ))"? Well, you can create some
       macros that allow you such a strange syntax. Note that the
       double-brackets are part of the syntax and cannot be removed! The set of
       three macros (plus two internal helper macros) also provides bool_and
       and bool_or. That given, what is it good for? We have && and || already,
       why do we need such a stupid syntax? Well, && and || can't guarantee
       that the arguments are converted to bool and that you get a bool result.
         Think "operator overloads". Here's how the macros look like:
    
       Note: BOOL_DETAIL_OPEN/CLOSE added to make it work on MSVC 2010
      */
    
    #define BOOL_DETAIL_AND_HELPER(x) static_cast(x):false
    #define BOOL_DETAIL_XOR_HELPER(x) !static_cast(x):static_cast(x)
    
    #define BOOL_DETAIL_OPEN (
    #define BOOL_DETAIL_CLOSE )
    
    #define bool_and BOOL_DETAIL_CLOSE ? BOOL_DETAIL_AND_HELPER BOOL_DETAIL_OPEN
    #define bool_or BOOL_DETAIL_CLOSE ? true:static_cast BOOL_DETAIL_OPEN
    #define bool_xor BOOL_DETAIL_CLOSE ? BOOL_DETAIL_XOR_HELPER BOOL_DETAIL_OPEN
    

提交回复
热议问题