2016-07-07 263 views
3

今天我試着將模板類傳遞給模板參數。我的模板類std::map有四個模板參數,但最後兩個是默認參數。模板類作爲模板參數默認參數

我能得到下面的代碼進行編譯:

#include <map> 

template<typename K, typename V, typename P, typename A, 
    template<typename Key, typename Value, typename Pr= P, typename All=A> typename C> 
struct Map 
{ 
    C<K,V,P,A> key; 
}; 

int main(int argc, char**args) { 
    // That is so annoying!!! 
    Map<std::string, int, std::less<std::string>, std::map<std::string, int>::allocator_type, std::map> t; 
    return 0; 
} 

不幸的是,我並不想通過最後兩個參數所有的時間。這實在太多了。我如何在這裏使用一些默認的模板參數?

回答

5

你可以使用type template parameter pack(因爲C++ 11),以允許可變參數模板參數:

template<typename K, typename V, 
    template<typename Key, typename Value, typename ...> typename C> 
struct Map 
{ 
    C<K,V> key; // the default value of template parameter Compare and Allocator of std::map will be used when C is specified as std::map 
}; 

然後

Map<std::string, int, std::map> t; 
+0

非常感謝!我不知道這些新的可變模板。優雅而短小。 – Aleph0

3

並不理想,但:

#include <map> 

template<typename K, typename V, typename P, 
    typename A=typename std::map<K, V, P>::allocator_type, 
    template<typename Key, typename Value, typename Pr= P, typename All=A> typename C=std::map> 
struct Map 
{ 
    C<K,V,P,A> key; 
}; 

int main(int argc, char**args) { 
    Map<std::string, int, std::less<std::string>> t; 
    return 0; 
} 
+0

不錯,用戶需要替換'std :: less '。 – Aleph0