我正在实现一些基于模板的序列化。我为 实现了模板化函数std::map,但现在我使用的是std::unordered_map. 我宁愿不复制和粘贴整个函数,而只是更改参数类型。有没有办法制作一个只需要一张地图或一张无序地图的模板?
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);
}
Run Code Online (Sandbox Code Playgroud)