在嵌入式编程中,内存分配是我们想要避免的事情。所以使用像状态设计模式这样的设计模式很麻烦。如果我们知道我们将拥有多少个状态,那么我们可以使用放置新操作。但在本文中,函数式方法避免了所有内存操作。唯一的缺点是它仅适用于具有 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 一起工作?