How can I make a function that takes either a map or an unordered_map?

I am implementing template based serialization. I applied a templated function for std::map

, but now I am using std::unordered_map

. I would rather not copy and paste the whole function and just change the type of the parameter. Is there a way to make a template that only accepts a card or an unordered card?

+3


source to share


3 answers


template <typename MAP>
void generic_foo(MAP& map)
{
    // generic implementation of your function
    // that works with unordered_map and map

    using K = typename MAP::key_type;
    using T = typename MAP::mapped_type;
}

// matches any possible implementation of std::unorderd_map
template <class Key,                                    
          class T,                                   
          class Hash,                       
          class Pred,                  
          class Alloc>
void foo(std::unordered_map<Key, T, Hash, Pred, Alloc>& m)
{
    // signature matched! forward to your implementation
    generic_foo(m);
}

// matches any possible implementation of std::map        
template <class Key,                                    
          class T,                          
          class Compare,                  
          class Alloc>
void foo(std::map<Key, T, Compare, Alloc>& m)
{
    // signature matched! forward to your implementation
    generic_foo(m);
} 

      



LIVE DEMO

+4


source


Just overload the function as a non-templated function with one overload to take std::map

and the other to take std::unordered_map

. Let these two functions call a hidden template

one that accepts anything but can only be called by them. One way to do this is to hide it in anonymous namespace

.



+2


source


#include<type_traits>
template<typename T>
void foo(T t){
    static_assert(std::is_same<T, std::map</*some_type*/>::value
               || std::is_same<T, std::unordered_map</*some_type*/>::value,
                  "Foo can only get std::map or std::unordered_map.");
}

      

0


source







All Articles