Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ convert class to boolean

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.

like image 211
wyatt Avatar asked Jul 29 '10 06:07

wyatt


2 Answers

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.

like image 68
plats1 Avatar answered Sep 19 '22 14:09

plats1


You can define a user-defined conversion operator. This must be a member function, e.g.:

class MyClass {   operator int() const   { return your_number; }   // other fields }; 

You can also implement operator bool. However, I would STRONGLY suggest against doing it because your class will become usable in arithmetic expressions which can quickly lead to a mess. IOStreams define, for example, conversion to void*. You can test void* in the same way you can test a bool, but there are no language-defined implicit conversions from void*. Another alternative is to define operator! with the desired semantics.

In short: defining conversion operator sto integer types (including booleans) is a REALLY bad idea.

like image 20
zvrba Avatar answered Sep 19 '22 14:09

zvrba