2014-12-06 118 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