Easiest way to flip a boolean value?

前端 未结 13 1455
后悔当初
后悔当初 2020-12-04 08:31

I just want to flip a boolean based on what it already is. If it\'s true - make it false. If it\'s false - make it true.

Here is my code excerpt:

swi         


        
13条回答
  •  暖寄归人
    2020-12-04 09:16

    Clearly you need a flexible solution that can support types masquerading as boolean. The following allows for that:

    template    bool Flip(const T& t);
    

    You can then specialize this for different types that might pretend to be boolean. For example:

    template<>  bool Flip(const bool& b)  { return !b; }
    template<>  bool Flip(const int& i)    { return !(i == 0); }
    

    An example of using this construct:

    if(Flip(false))  { printf("flipped false\n"); }
    if(!Flip(true))  { printf("flipped true\n"); }
    
    if(Flip(0))  { printf("flipped 0\n"); }
    if(!Flip(1)) { printf("flipped 1\n"); }
    

    No, I'm not serious.

提交回复
热议问题