Why does the explicit bool operator allow me to use the ANY primitive type?

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?

+4
source share
2 answers

This looks like a VS error: an explicit statement should not be used in a cast to a type other than 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.

+3
source

= 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 = ?
}
+3

All Articles