Reputation: 5
I need help because I need to use a variable type that behaves like bool but allows a "undefined" value (x). I don't think such type exists. I think I should write a class for this new type and using objects of this class as my variables. I'm non really good at coding (I'm doing this in school) so I'm confused about how objects of the same class interact with each other.
I mean: if I have two bool variables, I know that if I need to know the result of "a AND b" I can write "c = a && b" and that's it. But how would this work for a class? Do I have to write a class method for every possible operation? What would the arguments of these functions be? I think it could be two objects of the class but I have no idea if it would make sense.
I would really appreciate any sort of help.
Sorry for my poor english and coding skills.
Upvotes: 0
Views: 318
Reputation: 3096
Check out Boost tribool
type.
It represents all true
, false
, and undefined
states.
It is more or less like a std::optional<bool>
. You can also implement it yourself in a class. You will need to understand how operator overloading works.
class SpecialBoolean {
public:
SpecialBoolean() : state(Undefined) {}
SpecialBoolean(bool value) : state(value? True : False) {}
SpecialBoolean operator&& (SpecialBoolean other) const {
if( state == Undefined || other.state == Undefined)
return SpecialBoolean();
else
return SpecialBoolean(state == True && other.state == True);
}
private:
enum States { False = 0, True = 1, Undefined = 2 };
States state;
};
// Test:
SpecialBoolean value = SpecialBoolean() && SpecialBoolean(false);
Upvotes: 2