Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::optional returning a bool value doesn't always work

Tags:

c++

boost

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

like image 915
BubbleBoy Avatar asked Jun 27 '26 22:06

BubbleBoy


1 Answers

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.

like image 179
Rakete1111 Avatar answered Jun 29 '26 10:06

Rakete1111