I’m stuck on evaluating a struct as a bool in c++
struct foo {
int bar;
};
foo* x = (foo*)malloc(sizeof(foo));
int y = ( x ) ? 3 : 4;
This is what happens when it is ran:
could not convert 'x' from 'foo' to 'bool'
When searching for bool operators, I can only find ways to overload the comparator bool operator. Is there a straight up evaluate struct as a bool operator?
I also want to keep foo as plain old data if possible.
This can’t be the correct code for that error. The error states that it can’t convert
xfromfootobool, butxis not afoo, it is afoo*. And afoo*is convertable to bool1, so there would be no error for the code you have given.If you want to be able to use a
fooobject as a conditional, you need to provideoperator boolmember function for yourfooclass:In this case, any
foowill always evaluate totrue. This conversion toboolis considered “unsafe” because your object may be converted toboolin some unexpected places. To get around this, in C++03 you can use the safe bool idiom and in C++11 you can mark youroperator boolasexplicit:The
explicit operator boolwill still be used automatically in certain places, such as as a condition inifstatements andwhileloops. There are other answers that cover this.