【问题标题】:C++ How to implement a compile time mapping from types to types?C++ 如何实现从类型到类型的编译时映射?
【发布时间】:2021-10-10 14:28:03
【问题描述】:

是否有编译时映射的规范/参考实现,它将类型映射到类型?

例如,我需要来自IBar -> IFooint -> IFoo 的类型映射。

在编译时,当给定 IBar 时,我可以选择 IFoo

如何使用 C++17 解决这个问题?

编辑:这是一个使用结构体https://godbolt.org/z/EEvrYd9PE的示例

【问题讨论】:

  • 你能展示一下你想如何使用它吗?
  • 您可以在一个地方定义它还是需要在许多标题中添加新类型?
  • @GuillaumeRacicot:一个地方就足够了。我知道编译时类型列表,并且需要一个编译时类型映射来进行类型选择。
  • 您需要如何访问地图?遍历它?使用密钥就可以了?
  • @GuillaumeRacicot:不需要迭代。只需简单的键查找。

标签: c++ template-meta-programming compile-time type-mapping


【解决方案1】:

您可以使用重载和返回类型定义一个。这就像一个地图数据结构,您可以为多种目的初始化和重用多种类型。

template<typename T>
struct type_tag {
    using type = T;
};

template<typename K, typename V>
struct pair {
    using first_type = K;
    using second_type = V;
};

template<typename Pair>
struct element {
    static auto value(type_tag<typename Pair::first_type>) -> type_tag<typename Pair::second_type>;
};

template<typename... elems>
struct type_map : element<elems>... {
    using element<elems>::value...;

    template<typename K>
    using find = typename decltype(type_map::value(type_tag<K>{}))::type;
};

你可以这样使用它:

using my_map = type_map<
    pair<int, float>,
    pair<char, double>,
    pair<long, short>
>;

static_assert(std::is_same_v<my_map::find<int>, float>);
static_assert(std::is_same_v<my_map::find<char>, double>);
static_assert(std::is_same_v<my_map::find<long>, short>);

Live example

它应该非常快,因为查找仅限于类的范围,并且使用编译器自己的重载决议。

【讨论】:

  • 太棒了!这就是我一直在寻找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多