2014-12-06 182 views
2

我有一個需要使用某種地圖的類。默認情況下,我想使用std::map,但我也想讓用戶能夠使用不同的東西(例如std::unordered_map或者甚至可能是用戶創建的)。帶默認參數的C++模板模板參數

所以我有一些代碼,看起來像

#include <map> 

template<class Key, template<class, class> class Map = std::map> 
class MyClass { 
}; 

int main() { 
    MyClass<int> mc; 
} 

但隨後,G ++抱怨

test.cpp:3:61: error: template template argument has different template parameters than its corresponding template template parameter 
template<class Key, template<class, class> class Map = std::map> 
                  ^
test.cpp:8:14: note: while checking a default template argument used here 
    MyClass<int> mc; 
    ~~~~~~~~~~~^ 
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/map:781:1: note: too many template parameters in template template argument 
template <class _Key, class _Tp, class _Compare = less<_Key>, 
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
test.cpp:3:21: note: previous template template parameter is here 
template<class Key, template<class, class> class Map = std::map> 
        ^~~~~~~~~~~~~~~~~~~~~~ 
1 error generated. 

所以它看起來像g++是不滿,認爲std::map有默認參數。

有沒有辦法讓Map成爲可以接受至少兩個模板參數的模板?

如果可以的話,我寧願堅持使用C++ 98,但我願意接受C++ 11。

+1

如果你打開C++ 11,你可以說'模板類地圖=的std :: map',但真正的解決辦法是參數化的類型,而不是一個模板。 – 2014-12-06 15:27:04

+0

@KerrekSB我原本是這樣做的,但我需要地圖和地圖。我也有這些默認的模板參數,但我認爲如果用戶可以指定Map,並且他們沒有指定Map 或Map ,那將自動確定。有沒有更好的方式避免模板模板參數? – math4tots 2014-12-06 15:45:26

+0

* [C++模板函數默認值]的可能重複(http://stackoverflow.com/questions/3301362/c-template-function-default-value)*。 – 2015-06-23 22:08:06

回答

4

問題是您的模板模板參數只有兩個模板參數,而不是map,它有四個。

template<class Key, template<class, class, class, class> class Map = std::map> 
class MyClass { 
}; 

或者

template<class Key, template<class...> class Map = std::map> 
class MyClass { 
}; 

Should compile
但是,爲避免出現此類問題,請嘗試改爲使用地圖類型,並通過相應的成員typedef提取密鑰類型。例如。

template <class Map> 
class MyClass { 
    using key_type = typename Map::key_type; 
}; 
+0

謝謝! g ++很高興。但是,這禁止'Map'類型可選地接受模板模板參數或類型以外的任何其他參數?出於好奇,有沒有辦法讓'Map'的可選參數成爲任何東西? – math4tots 2014-12-06 15:40:05

+0

@ 0x499602D2這正是我在我的文章的最後一句中提出的。 – Columbo 2014-12-06 15:40:05

+0

@ math4tots不,那是不可能的。 (也有一個流行的未答覆的SO帖子,關於這個問題的確切地方...)這就是爲什麼你應該採取地圖類型,沒有模板。這非常靈活。 – Columbo 2014-12-06 15:40:40