mercredi 9 août 2017

Template function to receive a generic map as a parameter

There may be many case in which we want to perform some operation on a std::map or a std::unordered_map that is exactly the same, independently from the type of the map. Let us consider the following example:

#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;
}

If I try to compile the example above, I have this:

error: no matching function for call to ‘printMap(std::map<int, long int>&)’

I read about the use of template of template in this post. What is the right way to do that?

Aucun commentaire:

Enregistrer un commentaire