std::optional 和 boost::optional 的值是变体时的区别

Difference between std::optional and boost::optional when its value is a variant

在嵌入式编程中,内存分配是我们想要避免的事情。所以使用像状态设计模式这样的设计模式是很麻烦的。如果我们知道我们将拥有多少个状态,那么我们就可以使用 placement new 操作。但是在这个 article the functional approach avoids all memory manipulations. Only drawback is that it is only for users that have C++17 availability. I tried to use boost::variant and boost::optional with c++11, but a conversion operator is missing like in in this minimal example 中(这里使用带有 c++17 的 MSVC 编译但不是最新的 std):

#include <string>
#include <boost/variant.hpp>
#include <boost/optional.hpp>


boost::optional<boost::variant<int, std::string>> f()
{
   return 5;
}


int main()
{
    auto ret = *f();
    return *boost::get<int>(&ret);
}

错误信息:

error: no viable conversion from returned value of type 'int' to function return type 'boost::optional<boost::variant<int, std::string>>' (aka 'optional<variant<int, basic_string<char>>>')
return 5;

但是如果我用 std::optional 替换 boost::optional 它编译正常: compiling example 有人可以解释一下它们之间的区别吗?我怎样才能让它与 boost 一起工作?

boost::optional doesn't have a constructor that takes arguments to pass to the underlying type but std::optional 确实(见构造函数编号 8)

您需要显式调用可选的构造函数:

boost::optional<boost::variant<int, std::string>> f()
{
    return boost::optional<boost::variant<int, std::string>>{5};
}

或者由于包含的值类型的构造是非显式的:

boost::optional<boost::variant<int, std::string>> f()
{
    return boost::variant<int, std::string>{5};
}