Does if (static_cast<bool>(x))
make sense for some type of x?
Obviously if x
is a bool
, static_cast
is not required.
If x
is a raw pointer or std::unique_ptr
or std::shared_ptr
, then if (x)
is alright (especially since std::unique_ptr
and std::shared_ptr
both have a bool
operator). Maybe if (x != nullptr)
might be better.
If x
is an int
, I guess if (x != 0)
is preferred.
If x
is a double
, I guess if (x != 0.0)
is preferred (although checking for exact floating point values has its own issues).
If x
is some enum, if (x != E())
or if (x != E::whatever)
probably is better than static_cast<bool>
.
Are there any reasons to use if (static_cast<bool>(x))
for custom types (structs or classes) convertible to bool
?
AFAIK the C++ Core Guidelines do not mention static_cast<bool>
explicitly. I'm aware of following discussions:
if (static_cast<bool>(x)) vs if (x) (which covers pointers only) and
int to bool casting