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?
source to share
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);
}
source to share
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
.
source to share