I'm writing some code that necessitates my caching an exception.
Please consider
int main()
{
std::exception_ptr ex;
bool b = ex;
}
This doesn't compile due to ex
not being convertible to a bool
type. My current workaround is to write
bool b = !!ex;
or even
bool b = ex ? true : false;
The first way is ugly, the second one a tautology surely. I'm starting to blame the compiler (MSVC2015). Two things:
Is there a better way of checking if ex
has been set to an exception?
(Related) Do I need to initialise ex
in some way?
Read the documentation.
The implicit conversion is prohibited, but an explicit one is not.
std::exception_ptr is not implicitly convertible to any arithmetic, enumeration, or pointer type. It is contextually convertible to bool, and will evaluate to false if it is null, true otherwise.
Hence it works when you explicitly convert the expression, but not when you attempt to do so implicitly, i.e. in the bool
copy-initialization.
A better solution is to initialise the bool
directly:
bool b{ex};
Your P45 is in the post; hopefully you'll consult documentation in your next job. ;)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments