3

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!

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
Tamer Shlash
  • 9,030
  • 4
  • 42
  • 79

3 Answers3

7

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

Or write:

if (!!f)
   // Do something
Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
3

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();
  }
};
Community
  • 1
  • 1
Xeo
  • 126,658
  • 49
  • 285
  • 389
2
operator bool() { //implementation };
André Puel
  • 8,263
  • 8
  • 46
  • 82