首页 > 解决方案 > 用另一个布尔值提升可选

问题描述

我正在尝试编译类似的东西:

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;
}

是否有可能实现它 - 将有效对象存储在变量中并将其分解为布尔值?

标签: c++boostboost-optional

解决方案


您可以将您的更改whilefor

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

推荐阅读