And*_*ldo 4 c++ templates stdmap template-templates c++11
可能存在许多情况,其中我们想要在a std::map或std::unordered_map完全相同的情况下执行某些操作,而与地图的类型无关.让我们考虑以下示例:
#include <map>
#include <unordered_map>
#include <iostream>
template< template <typename,typename> class Container >
void printMap(Container<int, long> inputMap, bool additionalParam = false)
{
for (const pair<int,long> p : inputMap)
cout<<p.first <<","<< p.second <<std::endl;
}
int main()
{
int a = 1;
long b = 2;
map<int,long> map1;
map1.emplace(a,b);
unordered_map<int,long> map2;
map2.emplace(a,b);
printMap(map1);
printMap(map2);
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试编译上面的例子,我有这个:
error: no matching function for call to ‘printMap(std::map<int, long int>&)’
Run Code Online (Sandbox Code Playgroud)
我在这篇文章中读到了模板模板的使用.这样做的正确方法是什么?
试试
template< template <typename...> class Container, typename ... Ts >
void printMap(Container<int, long, Ts...> inputMap,
bool additionalParam = false)
Run Code Online (Sandbox Code Playgroud)
您代码中的(更大的)问题是 std::map和std::unordered_map是具有四个(而不是两个)模板参数的模板类。第三个和第四个具有默认值,因此您可以将std::map对象定义为
std::map<int, long> map1;
Run Code Online (Sandbox Code Playgroud)
但是,使用默认参数,您将其定义为
std::map<int, long, std::less<int>,
std::allocator<std::pair<const int, long> >> map1;
Run Code Online (Sandbox Code Playgroud)
(ps:或者你可以让它变得简单和使用auto,就像在 Semyon Burov 的解决方案中一样;+1)
如果您以这种方式定义,编译器无法推断模板参数.尝试使用:
template<typename Map>
void printMap(const Map& map, bool additionalParam = false) {
for (const auto& p : map)
cout<<p.first <<","<< p.second <<std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果你需要检查,Map确切地说Map<int, long int>,那么将静态断言添加到函数体:
static_assert( std::is_same< typename Map::key_type, int >::value &&
std::is_same< typename Map::mapped_type, long >::value, "!");
Run Code Online (Sandbox Code Playgroud)