有人可以推荐一种更优雅的方式来实现这些编译时常量吗?
template <int> struct Map;
template <> struct Map<0> {static const int value = 4;};
template <> struct Map<1> {static const int value = 8;};
template <> struct Map<2> {static const int value = 15;};
template <int> struct MapInverse;
template <> struct MapInverse<4> {static const int value = 0;};
template <> struct MapInverse<8> {static const int value = 1;};
template <> struct MapInverse<15> {static const int value = 2;};
我的程序中的值需要是 constexpr,但反向映射的值更新起来很繁琐(而且很容易出错甚至忘记做)。
最佳答案
在这个 C++11 解决方案中,所有映射项都保存在 constexpr
数组中,并且有 constexpr
递归函数可以通过键或值进行搜索。
#include <utility>
using Item = std::pair<int, int>;
constexpr Item map_items[] = {
{ 6, 7 },
{ 10, 12 },
{ 300, 5000 },
};
constexpr auto map_size = sizeof map_items/sizeof map_items[0];
static constexpr int findValue(int key, int range = map_size) {
return
(range == 0) ? throw "Key not present":
(map_items[range - 1].first == key) ? map_items[range - 1].second:
findValue(key, range - 1);
};
static constexpr int findKey(int value, int range = map_size) {
return
(range == 0) ? throw "Value not present":
(map_items[range - 1].second == value) ? map_items[range - 1].first:
findKey(value, range - 1);
};
static_assert(findKey(findValue(10)) == 10, "should be inverse");
关于c++ - 编译时映射和逆映射值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075969/