【问题标题】:How to make nested maps of variable depth如何制作可变深度的嵌套地图
【发布时间】:2014-05-12 14:04:10
【问题描述】:

我希望能够创建一个值是另一个 std::map 的 std::map,并且我希望能够将此映射嵌套到任意深度。

这是一个基本的例子:

std::map < std::string, std::map < std::string, int> > d1;

//       so the next depth would be.

std::map < std::string, std::map < std::string, std::map < std::string, int> > > d2;

我知道这对于固定长度很简单,但我不确定如何构建可变深度。

【问题讨论】:

  • 你能举例说明如何使用这样的类吗?

标签: c++ map nested stdmap


【解决方案1】:

由于我们不能专门化using,所以我们必须使用class + typedef 的老方法,最后用using 公开它:

template<typename Key, typename Value, unsigned int N>
struct VarMapHelper
{
    typedef std::map<Key, typename VarMapHelper<Key, Value, N-1>::type> type;
};

template<typename Key, typename Value>
struct VarMapHelper<Key, Value, 1>
{
    typedef std::map<Key, Value> type;
};

template<typename Key, typename Value, unsigned int N>
using VarMap = typename VarMapHelper<Key, Value, N>::type;

像这样使用它:

VarMap<std::string, int, 3> map;

为了防止将类误用为 VarMap&lt;std::string, int, 0&gt; 时编译器崩溃,我们也可以为 0 提供一个特化:

template<typename Key, typename Value>
struct VarMapHelper<Key, Value, 0>
{
    static_assert(false, "Passing variable depth '0' to VarMap is illegal");
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多