我正在编写一个函数,它应该接收 (std::map
、std::multimap
、std::unordered_map
或std::unordered_multimap
)。我的代码如下:
template<template <class, class> class Map, typename Coord>
inline typename std::enable_if<std::is_arithmetic<Coord>::value>::type
filter(Map<Coord, Coord>& map, Coord step = 2) {
for (auto it = std::begin(map); it != std::end(map);) {
if (it->second - it->first <= step){
it = map.erase(it);
}
else
++it;
}
}
模板模板参数Map
并没有概括所有类型的 map 。 std::map
和 std::multimap
接收四个模板参数,而 std::unordered_map
和 std::unordered_multimap
接收五个模板参数。这意味着我无法用模板模板参数解决问题。有没有办法解决这个问题,所有 map 都必须有 KeyType = ValeType = Coord
的约束?我不想在调用 filter
时明确指定参数类型。
最佳答案
你标记了 c++11,所以我会尝试使用可变模板参数:
template<template <class ... > class Map, typename Coord, typename ... MapParms >
inline typename std::enable_if<std::is_arithmetic<Coord>::value>::type
filter(Map<Coord, Coord, MapParms... >& map, Coord step = 2)
{
for (auto it = std::begin(map); it != std::end(map);)
{
if (it->second - it->first <= step)
{
it = diagram.erase(it);
}
else
{
++it;
}
}
}
关于c++ - 接收任何标准 map 的功能模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374670/