Template function to get a shared map as a parameter

There may be many cases where we want to perform some operation on std::mapor std::unordered_map, which will be exactly the same, regardless of the type of card. 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 above example, I have the following:

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

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

+4
source share
3 answers

The compiler cannot output the template argument if you define it. Try using:

template<typename Map>
void printMap(const Map& map, bool additionalParam = false) {
    for (const auto& p : map)
        cout<<p.first <<","<< p.second <<std::endl;
}

, 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, "!");
+5

template< template <typename...> class Container, typename ... Ts >
void printMap(Container<int, long, Ts...> inputMap,
              bool additionalParam = false)

() , std::map std::unordered_map ( ) . , std::map

 std::map<int, long> map1;

 std::map<int, long, std::less<int>,
          std::allocator<std::pair<const int, long> >> map1;

(ps: auto, ; +1)

+4

:

template<class Container>
void printMap(const Container& inputMap)
{
    using Key = typename Container::key_type; 
    using Value = typename Container::mapped_type;
    for (const std::pair<Key,Value> p : inputMap)
        std::cout << p.first << "," << p.second << std::endl;
}

, :

template<class Container>
void printMap(const Container& inputMap)
{
    for (const auto& p : inputMap)
        std::cout << p.first << ","<< p.second << std::endl;
}
0

Source: https://habr.com/ru/post/1683381/


All Articles