Double Negation in C++

后端 未结 14 2949
你的背包
你的背包 2020-11-22 10:40

I just came onto a project with a pretty huge code base.

I\'m mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic.

14条回答
  •  再見小時候
    2020-11-22 10:58

    This may be an example of the double-bang trick, see The Safe Bool Idiom for more details. Here I summarize the first page of the article.

    In C++ there are a number of ways to provide Boolean tests for classes.

    An obvious way is operator bool conversion operator.

    // operator bool version
      class Testable {
        bool ok_;
      public:
        explicit Testable(bool b=true):ok_(b) {}
    
        operator bool() const { // use bool conversion operator
          return ok_;
        }
      };
    

    We can test the class,

    Testable test;
      if (test) 
        std::cout << "Yes, test is working!\n";
      else 
        std::cout << "No, test is not working!\n";
    

    However, opereator bool is considered unsafe because it allows nonsensical operations such as test << 1; or int i=test.

    Usingoperator! is safer because we avoid implicit conversion or overloading issues.

    The implementation is trivial,

    bool operator!() const { // use operator!
        return !ok_;
      }
    

    The two idiomatic ways to test Testable object are

      Testable test;
      if (!!test) 
        std::cout << "Yes, test is working!\n";
      if (!test2) {
        std::cout << "No, test2 is not working!\n";
    

    The first version if (!!test) is what some people call the double-bang trick.

提交回复
热议问题