类似枚举的计算常量

Enum like calculated constants

本文关键字:计算 常量 枚举      更新时间:2023-10-16

实际上,这个"问题"感觉非常简单。在计算图标偏移量时,我想出了以下方法:

namespace Icons {
struct IconSet {
constexpr IconSet(size_t base_offset) noexcept
: base_offset_(base_offset), icon(base_offset * 3), iconSmall(icon + 1), iconBig(icon + 2) {
}
size_t icon;
size_t iconSmall;
size_t iconBig;
size_t base_offset_;
constexpr size_t next() const {
return base_offset_ + 1;
}
};

static constexpr IconSet flower = IconSet(0);
static constexpr IconSet tree = IconSet(flower.next());
static constexpr IconSet forest = IconSet(tree.next());
static constexpr IconSet mountain = IconSet(forest.next());
}

现在可以写CCD_ 1来获得该图标的计算偏移量。基本上,设计师可以更改图标,有时也可以添加/删除图标,但必须按照惯例提供整个图标集(普通、小和大(。

正如您所看到的,这种方法的问题在于,我必须执行next()函数并重复使用它——普通枚举不会有这种缺点。

我知道BOOST_PP和其他宏技巧,但我希望有一些没有宏的东西——因为我觉得不需要它,然后我有点喜欢我已经拥有的普通next()函数。另一种解决方案当然只是一个普通的枚举和一个计算函数,但这会破坏预先计算好的布局目的。

因此,我正在寻找一个简单且可移植的解决方案,它将提供类似枚举的功能。它不必是编译时或constexpr,例如,如果只是内联会使它更容易。

以下是一种可以使用的方法,它基于编译时整数序列上的fold表达式,通过索引实例化图标。结构化绑定可以为您单独命名非静态、非constexpr变量。

Icons中的匿名命名空间使这些定义仅在此翻译单元中可见,您可能需要也可能不需要。

编译器资源管理器链接,以便您可以自己探索代码选项。

#include <cstddef>
#include <array>
#include <utility>
namespace Icons {
struct IconSet {
constexpr IconSet(size_t base_offset) noexcept 
: base_offset_(base_offset), icon(base_offset * 3), iconSmall(icon + 1), iconBig(icon + 2) {
}
size_t icon;
size_t iconSmall;
size_t iconBig;
size_t base_offset_;
};
template <std::size_t... Ints>
constexpr auto make_icons_helper(std::index_sequence<Ints...>) -> std::array<IconSet, sizeof...(Ints)> 
{
return {IconSet(Ints)...};
}
template <size_t N>
constexpr auto make_icons()
{
return make_icons_helper(std::make_index_sequence<N>{});
}
namespace {
auto [flower, tree, forest, mountain] = make_icons<4>();
}
}
int main()
{
return Icons::forest.iconSmall;
}

一个简单的、非常量的解决方案,使用静态计数器,并依赖于在单个TU:内自上而下执行静态初始化的事实

namespace Icons {
namespace detail_iconSet {
static std::size_t current_base_offset = 0;
}
struct IconSet {
IconSet() noexcept 
: base_offset_(detail_iconSet::current_base_offset++)
, icon(base_offset_ * 3)
, iconSmall(icon + 1)
, iconBig(icon + 2) { }
std::size_t base_offset_;
std::size_t icon;
std::size_t iconSmall;
std::size_t iconBig;
};

static IconSet flower;
static IconSet tree;
static IconSet forest;
static IconSet mountain;
}

在Coliru 上实时观看

问题是,如果您有几个包含IconSet定义的标头(即,它们的编号将根据包含的顺序而变化(,这种情况会表现得很奇怪,但我认为没有办法避免这种情况。