class my_bool {
private:
bool value;
public:
my_bool(bool value) : value(value) {}
operator bool();
friend my_bool operator==(const my_bool & instance_1, const my_bool & instance_2);
};
void main(){
my_bool a = true;
bool b = false;
if(a == b){
// do something
}
}
The compiler says that comparison operator is ambiguous. Compiler cannot decide whether a
should be converted to bool
or b
should be converted to my_bool
. Is there a way I can solve this problem without writing down 3 overloads ( my_bool
, my_bool
), ( bool
, my_bool
), ( my_bool
, bool
) of the same comparison operator?
Remove the const
qualifer on the second second parameter to get rid of the ambiguity:
friend my_bool operator==(const my_bool & instance_1, my_bool & instance_2);
Or use explicit
explicit operator bool();
Or use a different ==
overload that make more sense like this:
class my_bool
{
private:
bool value;
public:
my_bool(bool value) : value(value) {}
operator bool() { return value; }
bool operator == (bool val)
{
return this->value == val;
}
};
You could explicitly convert a
to a bool
if(((bool) a) == b){ // yes, this is a cast.
// do something
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.