lancegerday
lancegerday

Reputation: 762

How to make nested maps of variable depth

I want to be able to create an std::map with a value that is another std::map and I want to to be able to nest this map to an arbitrary depth.

Here is a basic example:

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;

I know this is simple to do for fix length but am unsure of how to approach building one of variable depth.

Upvotes: 3

Views: 1350

Answers (1)

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11502

As we cant specialize using, we have to go the old way with class + typedef and expose it with using in the end:

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;

Use it like:

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

To prevent a compiler crash if one misuses the class as VarMap<std::string, int, 0> we can provide a specialization for 0 aswell:

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

Upvotes: 3

Related Questions