Search code examples
c++boostgoogletestboost-optional

Boost Optional implicit conversion to bool?


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?


Solution

  • 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.