I encountered an issue that I was unable to figure out, hope someone can help (gcc 4.7.2, boost 1.59)
bool IsValidTest(int val) const
{
if(val > 0)
return func(); // func() returns boost::optional<SomeType>;
}
I would expect that the optional is implicitly converted to bool , but the compiler complains
error: cannot convert boost::optional<SomeType> to bool in return
I did see that the ! operator existed so a solution would be to use
return !!func();
Now, what I cant figure out is why the above won't compile and the following will, why the issue converting to bool when returning from the function
if(func())
// optional actually exists
Note: I also noticed that IsValidTest() did not give any compilation error on visual studio
Any help much appreciated
boost::optional defines an explicit operator bool.
explicit means that the compiler will not do the implicit conversion for you, you have to specify that you want to call the operator.
You used !!, but you could have also used static_cast<bool>(). It works for if because the if statement has special rules regarding operator bool, namely that it ignores the explicit identifier when evaluating its expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With