boost 是否有按特殊类型值编码状态"compact optional"?

Does boost have an "compact optional" where presence is encoded by special value of type?

本文关键字:状态 编码 compact optional 类型 是否 boost      更新时间:2023-10-16

我正在寻找可选的(sizeof small_optional<T> == sizeof (T)(的节省空间的实现。 因此,空性是使用T的一些特殊值进行编码的,例如

small_optional<int, -1> 

要求我从不将 -1 存储在small_optional因此 -1 可以用作魔术值来确定可选是否为空。

可标记的库就是为了这个目的而创建的:

可标记 1.0.0

boost::optional<T>的替代方法,它不存储额外的bool标志,而是使用特殊的指示值对T内部的"空"状态进行编码。

用法

是否要存储可能丢失的int?你能节省有价值的-1吗? 你可以像这样使用它:

using namespace ak_toolkit;
typedef markable<mark_int<int, -1>> opt_int;
opt_int oi;
opt_int o2 (2);
assert (!oi.has_value());
assert (o2.has_value());
assert (o2.value() == 2);
static_assert (sizeof(opt_int) == sizeof(int), "");

是否要存储可能丢失的std::string,其中"丢失" !="空"?你能省出一些包含空值的字符串值吗 里面的性格,像std::string("", 2)?这就是你的做法 它:

struct string_marked_value                           // a policy which defines the representaioion of the
: ak_toolkit::markable_type<std::string>           // 'marked' (special) std::string value
{               
static std::string marked_value() {                // create the marked value
return std::string("", 2);
}
static bool is_marked_value(const std::string& v) { // test if a given value is considered marked
return v.compare(0, v.npos, "", 2) == 0;
}
};
typedef ak_toolkit::markable<string_marked_value> opt_str;
opt_str os, oE(std::string(""));
assert (!os.has_value());
assert (oE.has_value());
assert (oE.value() == "");
static_assert (sizeof(opt_str) == sizeof(std::string), "");

尽管不是 Boost 库,但 markable 在 Boost 软件许可证 1.0 版下获得许可,甚至可以从 Boost 自己的可选类型的性能注意事项部分引用:

性能注意事项

[...]

控制大小

[...]因此,如果对象的大小对您的 应用程序(例如,因为您想在 为了获得性能(,并且您已经确定您愿意 交易代码清晰,建议你直接去 键入int并使用一些"魔术值"来表示非整数,或 使用类似可标记的东西 图书馆。


lib 的背景和思维过程在 lib 作者的以下博客文章中进行了解释:

  • Andrzej 的C++博客 - 高效的可选值