我正在实现一些基于模板的序列化。我为 std::map
实现了模板化函数,但现在我使用的是 std::unordered_map
。我宁愿不复制和粘贴整个函数而只更改参数类型。有没有办法制作一个只需要一张 map 或一张无序 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);
}
关于c++ - 我如何创建一个接受 map 或 unordered_map 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25749917/