可能有很多情況下,我們想要在與映射類型無關的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;
}
如果我嘗試編譯上面的例子,我有這樣的:
error: no matching function for call to ‘printMap(std::map<int, long int>&)’
我讀到這個post使用模板的模板。什麼是正確的方法來做到這一點?
['std :: map'](http://en.cppreference.com/w/cpp/container/map)有兩個以上的模板參數。你還有一個'比較'類型和'Allocator'類型。你必須指定所有的,甚至是默認的。 –
請注意,您的代碼將正常工作來C++ 17;以下解決方案都適用於C++ 14及更低版本。 –