如何制作可变深度的嵌套地图

时间:2014-04-01 16:46:04

标签: c++ map nested stdmap

我希望能够创建一个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;

我知道修复长度很简单但不确定如何构建可变深度的方法。

1 个答案:

答案 0 :(得分:2)

由于我们无法专注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<std::string, int, 0>,我们可以为0提供专门化:

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