Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a struct as an operand of a conditional?

I have a simple struct in C++11

struct a {
    int a;
    int b;
    int c;
    ....
}

I would like to use this struct as if it is an scalar type itself, so I overloaded all operators.

One behaviour I can't find how to define is the use of a struct in an if statement:

a v = {1,2,3};
if (v) { }

Is there an operator that I can overload to enable this behaviour? I want the standard behaviour: if any bit is 1 in the struct it's true, else it's false.

like image 345
Peter Smit Avatar asked Aug 22 '14 09:08

Peter Smit


1 Answers

Add an explicit boolean conversion:

struct a
{
    explicit operator bool() const
    {
        return a || b || c;
    }

    int a;
    int b;
    int c;
    // ...
};
like image 188
Kerrek SB Avatar answered Sep 17 '22 22:09

Kerrek SB