Tamer Shlash
Tamer Shlash

Reputation: 9523

Is there a "normal" unary logical operator in C++

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!

Upvotes: 3

Views: 238

Answers (3)

Xeo
Xeo

Reputation: 131799

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();
  }
};

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

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

Or write:

if (!!f)
   // Do something

Upvotes: 7

André Puel
André Puel

Reputation: 9179

operator bool() { //implementation };

Upvotes: 2

Related Questions