سؤال

I mean, we all know that there is the negation logical operator !, and it can be used like this:

class Foo
{
public:
    bool operator!() { /* implementation */ }
};

int main()
{
    Foo f;
    if (!f)
        // Do Something
}

Is there any operator that allows this:

if (f)
    // Do Something

I know it might not be important, but just wondering!

هل كانت مفيدة؟

المحلول

You can declare and define operator bool() for implicit conversion to bool, if you're careful.

Or write:

if (!!f)
   // Do something

نصائح أخرى

Since operator bool() in itself is pretty dangerous, we usually employ something called the safe-bool idiom:

class X{
  typedef void (X::*safe_bool)() const;
  void safe_bool_true() const{}
  bool internal_test() const;
public:
  operator safe_bool() const{
    if(internal_test())
      return &X::safe_bool_true;
    return 0;
  }
};

In C++11, we get explicit conversion operators; as such, the above idiom is obsolete:

class X{
  bool internal_test() const;
public:
  explicit operator bool() const{
    return internal_test();
  }
};
operator bool() { //implementation };
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top