4

I'm reading some code and I came across something I do not understand. Its about testing if a Boost::optional value is initialised or not. It uses the gtest framework which provides the ASSERT_TRUE() macro.

#include "gtest\gtest.h"

void test() {
    boost::optional<someClass> opt = someFunc();
    ASSERT_TRUE(!!opt);
}

Why do I need the !! before opt? Is a boost::optional not implicitly converted to a bool, which is needed by the macro? I thought it would be enough to use ASSERT_TRUE(opt) to check if opt holds a correct value?

Antonio Pérez
  • 6,702
  • 4
  • 36
  • 61
Ventu
  • 780
  • 1
  • 12
  • 25

1 Answers1

9

Is a boost::optional not impicit converted to a bool

No, it's not. Its conversion operator to bool is marked explicit, but your testing framework needs something that's implicitly convertible. You should see the problem with plain bool test = opt; too: that should fail to compile.

  • I understand, but if I read this post right: http://stackoverflow.com/questions/4923384/conversion-of-boostoptional-to-bool, it is implicit converted? Has this changed? – Ventu Jan 20 '16 at 23:28
  • 4
    @Suv `if(my_optional)` will compile even if the conversion operator is `explicit` because that's a [contextual conversion](http://en.cppreference.com/w/cpp/language/implicit_cast#Contextual_conversions). Also, depending on the version of Boost and whether you have c++11 enabled etc., `optional` might use the safe bool idiom for the bool conversion, which is also an implicit conversion, but prevents compilation of some questionable uses. – Praetorian Jan 20 '16 at 23:33