0

I have a Line that represents the relevant information of a line on the cartesian plane. The type that has, among other members, a bool that indicates whether the slope is defined. I would like to be able to do the following:

if(my_line){
   double new_slope = my_line.slope * 9;
}

where the instance my_line itself is implicitly converted to a true/false value in a boolean context. I am thinking of the behavior I see with smart pointers, where if it is pointing to nullptr or 0, the instance is considered false as-is.

How would I go about emulating this behavior?

Liam White
  • 121
  • 6

1 Answers1

1

In your Line class, implement a bool conversion operator. You could also optionally overload the operator!, but that is not required in C++11 and later. See Contextual conversions.

For example:

class Line {
    bool mSlopeDefined;
    ...

public:
    ...

    explicit operator bool() const noexcept {
        return mSlopeDefined;
    }

    // optional since C++11, but doesn't hurt...
    bool operator!() const {
        return !mSlopeDefined;
    }
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770