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.
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");
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With