Peter Smit
Peter Smit

Reputation: 28716

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.

Upvotes: 5

Views: 247

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476990

Add an explicit boolean conversion:

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

    int a;
    int b;
    int c;
    // ...
};

Upvotes: 16

Related Questions