2014-04-01 35 views
3

我希望能夠使用另一個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; 

我知道這是簡單的固定長度做的,但我不確定如何處理建築可變深度的一個。

+0

你能舉一個例子說明如何使用這樣的類嗎? – Brian

回答

2

正如我們不能專注using,我們必須去舊的方式與class + typedefusing最終將其暴露:

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; 

爲防止編譯器崩潰,如果誤用e類作爲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"); 
};