by implicit · 15y ago · 0 comments
Consider this program:
#include <iostream>
using std::cout;
using std::endl;
struct C {
int x;
C(int _x) : x(_x) {}
operator bool() const { return 0 != x; }
};
struct D {
float f;
D(float _f) : f(_f) {}
operator bool() const { return 0.0f != f; }
};
int main() {
C c(9);
D d(2.0f);
if (c == d) {
cout << "Equal" << endl;
}
return 0;
}
g++ 3.4.4 doesn't so much as warn that something is fishy here, even with -Wall.Not only that, but c and d are considered to be equal.
c.bool() == d.bool()
In this case both will return true since they are non-zero, and thus the statement would be
1 == 1
Which is true; the compiler did exactly as you told it to do.
I don't have a C++0x compiler handy, or I would test it, but I do believe explicit is only meant for cases such as this:
a + 1;
where a has a bool() operator that returns 1 or 0, in the old mode if there was no way to get a to be a number it would look at the operator bool() see that it returns a number and use that. Using explicit on the bool() operator would make that illegal and most likely a compiler error.
Are you saying that the funtion YOU wrote to convert C/D to a bool shouldn't be invoked when YOU are using C/D as booleans?
But it's confusing that they're being used as booleans at all. They're converted because it will let the types match even though the conversion doesn't make much sense.