struct test { explicit operator bool() const { return true; } }; int main() { test a; float b = static_cast<float>(a); // b = 1 }
Is this resolved correctly, or is it a VS error? If so designed, what is the best practice here? Should I do anything to prevent this?
This looks like a VS error: an explicit statement should not be used in a cast to a type other than bool.
bool
This does not compile in gcc in both C ++ 11 and C ++ 98 mode .
Can I do anything to prevent this?
You did what you need - this is a compiler problem.
= delete :
= delete
struct test { explicit operator bool() const { return true; } template<typename T> explicit operator T() const = delete; };
Coliru ( MSVC:))
int main() { test a; float b = static_cast<bool>(a); // b = 1 float c = static_cast<float>(a); // c = ? }