Mees de Vries Mees de Vries - 1 month ago 7
C++ Question

Make explicit when a struct is truthy or falsy in C++

I have defined a simple struct

mystruct
in C++. I would like to be able to use

mystruct a;
// do things to a
if(a) {
/* do things */
}


directly. Is there a way for me to define the behavior of this?

Answer

Is there a way for me to define the behavior of this?

Yes, provide an overload for the bool type conversion operator:

class mystruct {
public:
  operator bool () const {return condition; } // This is the conversion operator
};

This answer contains some more detailed info.