c++ convert class to boolean

wyatt picture wyatt · Jul 29, 2010 · Viewed 15.4k times · Source

With all of the fundamental types of C++, one can simply query:

if(varname)

and the type is converted to a boolean for evaluation. Is there any way to replicate this functionality in a user-defined class? One of my classes is identified by an integer, although it has a number of other members, and I'd like to be able to check if the integer is set to NULL in such a manner.

Thanks.

Answer

plats1 picture plats1 · Feb 3, 2016

The C++11 approach is:

struct Testable
  {
    explicit operator bool() const
      { return false; }
  };

int main ()
  {
    Testable a, b;
    if (a)      { /* do something  */ }  // this is correct
    if (a == b) { /* do something  */ }  // compiler error
  }

Note the explicit keyword which prevents the compiler from converting implicitly.