Alex Rivera | Logout

c++ convert class to boolean

Asked 2010-07-29T06:28:25.817
36

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.

Edit
Report

1 Answer

5

As others have stated, using operator int () or operator bool () is bad idea because of the conversions it allows. Using a pointer is better idea. The best know solution to this problem so far is to return a member (function) pointer:

class MyClass {
  void some_function () {}

  typedef void (MyClass:: * safe_bool_type) ();
  operator safe_bool_type () const
  { return cond ? &MyClass::some_function : 0; }
};
answered 2010-07-29T08:50:11.137

Your Answer