1

在嵌入式编程中,内存分配是我们想要避免的事情。所以使用像状态设计模式这样的设计模式很麻烦。如果我们知道我们将拥有多少个状态,那么我们可以使用放置新操作。但在本文中,函数式方法避免了所有内存操作。唯一的缺点是它仅适用于具有 C++17 可用性的用户。我尝试在 c++11 中使用 boost::variant 和 boost::optional,但是在这个最小示例中缺少转换运算符(这里使用带有 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 它编译得很好:编译示例 有人可以解释它们之间的区别是什么,我怎样才能让它也与 boost 一起工作?

4

1 回答 1

2

boost::optional没有将参数传递给基础类型的构造函数,但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};
}
于 2021-06-22T09:29:40.227 回答