Search code examples
c++boostboost-optional

boost optional with another boolean


I am trying to compile something akin to this:

struct Obj { int i = 100; };

boost::optional<Obj> f(const bool _b)
{
    if (_b) return Obj(); else return boost::none;
}

int main()
{
    bool run = true;
    while (boost::optional<Obj> retVal = f(true) && run)
    {
        std::cout << retVal.i;
    }

    return 0;
}

Is it possible to achieve it at all - to store a valid object in a variable and have it decomposed to a bool too?


Solution

  • You could change your while into a for like:

    for (boost::optional<Obj> retVal = f(true), retVal && run; retVal = f(true))
    {
        std::cout << retVal.i;
    }