3

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?

Mees de Vries
  • 639
  • 3
  • 24

1 Answers1

4

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:
  explicit operator bool () const {return condition; } // This is the conversion operator
};

This answer contains some more detailed info.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Thank you! I figured it would be something like this, but did not know the terminology to google it. – Mees de Vries Nov 01 '16 at 18:40
  • @MeesdeVries Totally understandible. The terminology gap is often a bigger problem than the problem you're solving. – user4581301 Nov 01 '16 at 18:45
  • I believe the `explicit` keyword (or the safe bool idiom for everyone who is stuck with a pre-C++11 compiler) should be mentioned, because it avoids a bunch of annoying problems of the non-explicit version. It’s part of the linked answer, but I believe it’s an important enough issue to at least mention it here as well. – besc Nov 01 '16 at 20:19
  • @besc Besides it's mentioned in the linked detailed info, i've added that to my sample. – πάντα ῥεῖ Nov 01 '16 at 20:21