c++ - 编译时映射和逆映射值

标签 c++ templates map meta inverse

有人可以推荐一种更优雅的方式来实现这些编译时常量吗?

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/

相关文章:

c++ - 加载从信号槽接收到的 QStringList 值

templates - Liferay Velocity 结构和模板。可重复字段

c++ - 条件类型别名定义

java - 如何正确使用同步链接 HashMap

ios - 如何在 ios 的 Xamarin 谷歌地图组件中处理点击事件

C++函数指针语法

c++ - const int*& var 是什么意思?

c++ - SFINAE : Derived class hide base class function depend on T

php - PHP 中的超轻型模板系统,不允许模板内的 php 代码或使用 eval

c++ - 制作一个值类型是 C++ 中的抽象类的映射